C++:: 将 ASCII 值转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18938740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:21:02  来源:igfitidea点击:

C++:: Convert ASCII value to string in

c++stringascii

提问by Kenneth Yang

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

我正在尝试将表示字符的 ASCII 值的 int 转换为单字符字符串。

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

我尝试了以下方法,但不起作用:
string s1=(char) 97;

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

但是,只有当我像这样将分配分开时,转换才有效:
string s1; s1=(char) 97;

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

我对此感到困惑,任何人都可以解释其中的区别吗?


Thanks in advance!


提前致谢!

回答by syam

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

我尝试了以下方法,但不起作用: string s1=(char) 97;

That's because the std::stringconstructordoesn'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).

那是因为std::string构造函数没有任何需要单个char. 而且,复制被省略,因此构造函数被直接调用,operator =()从不调用(在复制省略上记录自己)。

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

只有当我像这样将分配分开时,转换才有效: string s1; s1=(char) 97;

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

现在副本不再被省略,您实际上正在调用std::string::operator =()确实具有接受单个char.