【发布时间】:2020-06-24 19:12:41
【问题描述】:
我正在尝试将'd' 打印为 C++ 中的字符串。
string s = to_string((char)('a'+ 3));
cout << s << endl;
预期输出:"d"
实际输出:"100"
我无法理解这种行为。 任何帮助将不胜感激。
【问题讨论】:
-
请注意,
to_string没有覆盖字符,这就是为什么你的字符被提升为int,然后转换为字符串。
我正在尝试将'd' 打印为 C++ 中的字符串。
string s = to_string((char)('a'+ 3));
cout << s << endl;
预期输出:"d"
实际输出:"100"
我无法理解这种行为。 任何帮助将不胜感激。
【问题讨论】:
to_string 没有覆盖字符,这就是为什么你的字符被提升为int,然后转换为字符串。
std::to_string 是将整数 或浮点 值转换为字符串的函数。你不应该在这种情况下使用它。
简单使用
std::cout << 'a' + 3 << std::endl;
或者
char c = 'a' + 3;
std::cout << c << std::endl;
或者如果你真的希望将结果保存为字符串:
std::string s = std::string{'a' + 3};
std::cout << s << std::endl;
【讨论】:
你需要的是
std::string s( 1, 'a'+ 3 );
或
std::string s;
s += 'a'+ 3;
或者例如喜欢
std::string s( 1, 'a' );
s.back() += 3;
(有几种方法可以得到预期的结果)
至于这份声明
string s = to_string((char)('a'+ 3));
然后表达式 ( char )('a' + 3 ) 被隐式转换为 int 类型(由于整数提升和所选重载函数 std::to_string 的参数的类型),表示为调用 std::to_string 之后的字符串..
【讨论】:
'a' + 3 是 int 类型。 (char)('a' + 3) 在使用 ASCII 编码的平台上确实是 'd'。 Vlad 提出的观点是,to_string 没有过载,它需要char;最好的一个是带int 的那个。
std::string 有一个operator= 接受char,所以s += 'a' + 3; 可以是s = 'a' + 3;