不能直接在 C++ 中支持简洁的 int 和字符串?
can't support concated int and string directly in c++?
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
作为字符串。)
相关文章:
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 构造<int>具有 2 个字符串文字的向量
- 字符串中int的加法运算
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- cin >> int 给定一个字符串将 int 赋值为 0
- 将字符串中的 int 转换为字母;
- 使用 switch,但我想用字符串而不是 int 进行选择
- 两个数组,int 和 string,如何显示带有对应 int 的字符串?
- 从字符串流中读取具有特定字段宽度的 int
- win 表单应用程序字符串^ 到 int
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 将字符串转换为 int 后的随机值
- 如何检查字符串是否正确以将其转换为 int?
- 在乌鸦中获取非Int(字符串)URL资源ID
- 如何使 int 字符串中的每个输入都成为一位数
- 将无符号int+字符串强制转换为无符号char向量
- 如何在C++中连接字符串+int+字符串
- 如何在消息框中使用int字符串?
- 如何在C++中将向量转换为<int>字符串