string tmp=“abc”
string f;
f=""+tmp[0];
cout<<f;
why f gives a empty string can anyone explain
string tmp= “abc”;
string f;
f+=tmp[0];
cout << f;
Use f+=tmp[0] which means f = f+tmp[0] instead
what is wrong in
f=""+tmp[0];
this means f is assigned a string which contains first char in tmp.
even f=“a”+tmp[0];
is giving empty string
If it is only for assigning f to the first char then consider using f=tmp[0]; instead
f=""+tmp[0]; what is wrong in this I just cast a char to string using “”
The problem is you cannot directly add char (i.e temp[0]) to a string like that you will get a warning but your code will run.
warning-
adding ‘std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator>::value_type’ (aka ‘char’) to a string does not append to the string [-Wstring-plus-int]
Solution -
Assign “” to a string variable and things should work just fine.
string tmp=“abc”;
string f;
string b="";
f=b+tmp[0];
cout<<f;