如何将int赋值给具有字符串流的字符串

how do I assign an int to a string with stringstream?

本文关键字:字符串 int 赋值      更新时间:2023-10-16

如何将int分配给具有stringstreamstring

在以下示例中,"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;