Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++:: Convert ASCII value to string in

Tags:

c++

string

ascii

I am trying to convert an int that represents the ASCII value of a character to a single-character string.

I tried the following, and it does not work:
string s1=(char) 97;

However, the conversion works only if I break the assignment apart like this:
string s1; s1=(char) 97;

I am confused by this and can anyone explain the difference?


Thanks in advance!

like image 705
Kenneth Yang Avatar asked Sep 21 '13 23:09

Kenneth Yang


1 Answers

I tried the following, and it does not work: string s1=(char) 97;

That's because the std::string constructor doesn't have any overload that takes a single char. And also, copy is elided so the constructor is called directly, operator =() is never called (document yourself on copy elision).

the conversion works only if I break the assignment apart like this: string s1; s1=(char) 97;

Now the copy is not elided any more, you are really calling std::string::operator =() which does have an overload accepting a single char.

like image 195
syam Avatar answered Sep 18 '22 00:09

syam