不能直接在 C++ 中支持简洁的 int 和字符串?

can't support concated int and string directly in c++?

本文关键字:int 字符串 简洁 支持 C++ 不能      更新时间:2023-10-16
int x=10;
string str;
str+=x;
cout<<"hello"<<str<<endl;

为什么只打招呼,而不是Hello10?

不能在C ?

您需要将stringstream用于这种要求。

int x=10;
stringstream ss;//create a stringstream
ss << x;//add number to the stream
string str=ss.str();
cout<<"hello"<<str<<endl;//Will print hello10
return 0;

您首先需要将x转换为std::string

 string str = std::to_string(x) /* + "" */;

c 没有真正的字符类型;在C 中,字符是积分类型,当您向字符串添加一个数字时,它是考虑了字符代码。在大多数系统上,10对应到新行的字符代码,因此在您的示例中,str += x;将新的行字符附加到str。(对待任何作为char的算术类型可能不是一个好主意,但是自C的最早几天以来一直是这种情况,并且改变了鉴于数量代码会破裂。另一方面,使用++=格式非弦类型绝对是一个坏主意。)

如果您需要将非弦数据格式化为字符串,请使用 std::ostringstream。这也将允许您指定如何您想要格式化的东西。(有很多代表的方法数字值10作为字符串。)