Printing character after addition as string in C++

Viewed 184

I am trying to print 'd' as string in C++.

string s = to_string((char)('a'+ 3));

cout << s << endl;

Expected Output: "d"

Actual Output: "100"

I am unable to understand this behavior. Any help would be highly appreciated.

2 Answers

std::to_string is a function to convert integer or floating point values to strings. You shouldn't use it in this situation.

Use simply

std::cout << 'a' + 3 << std::endl;

Or

char c = 'a' + 3;
std::cout << c << std::endl;

Or if you really want the result to be saved as string:

std::string s = std::string{'a' + 3};
std::cout << s << std::endl;

What you need is

std::string s( 1, 'a'+ 3 );

or

std::string s;
s +=  'a'+ 3;

or for example like

std::string s( 1, 'a' );
s.back() +=  3;

(there are several ways to get the expected result)

As for this declaration

string s = to_string((char)('a'+ 3));

then the expression ( char )('a' + 3 ) is implicitly converted to an int type (due to integral promotions an the type of the argument of the selected overloaded function std::to_string) that is represented as a string after the call of std::to_string..

Related