如何将int赋值给具有字符串流的字符串
how do I assign an int to a string with stringstream?
如何将int
分配给具有stringstream
的string
?
在以下示例中,"stringstream(mystr2) << b;
"不会将b
分配给mystr2
:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string mystr = "1204";
int a;
stringstream(mystr) >> a;
cout << a << endl; // prints 1204
int b = 10;
string mystr2;
stringstream(mystr2) << b;
cout << mystr2 << endl; // prints nothing
return 0;
}
这应该做:
stringstream ss;
ss << a;
ss >> mystr;
ss.clear();
ss << b;
ss >> mystr2;
int b = 10;
string mystr2;
stringstream ss;
ss << b;
cout << ss.str() << endl; // prints 10
使用ctor stringstream(mystr2)
创建字符串流时,mystr2
将被复制为缓冲区的初始内容。CCD_ 9不会被流上的后续操作所修改。
要获取流的内容,可以使用str
方法:
int b = 10;
string mystr2;
stringstream ss = stringstream(mystr2);
ss << b;
cout << mystr2.str() << endl;
请参阅构造函数和str方法。
这将正确打印出下面的"10"。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string mystr = "1204";
int a;
stringstream(mystr) >> a;
cout << a << endl; // prints 1204
int b = 10;
string mystr2;
stringstream ss;
ss << b;
ss >> mystr2;
cout << mystr2 << endl; // prints 10
return 0;
}
您的字面问题的答案是:
int b = 10;
std::string mystr2 = static_cast<stringstream &>(stringstream()<<b).str();
cout << mystr2 << endl;
相关文章:
- 我如何获取从 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?
- 在 c++ 中逐个字符从字符串传递到 int 时不精确
- <int> 使用 fmt 库将向量转换为字符串
- 我正在尝试将 int 值插入字符串,而不是 1,我得到 10
- 为什么编译:字符串 = int
- C++ 隐式类型转换字符串 -> int?
- 如何在C++中连接字符串+int+字符串