简体   繁体   English

如何使用stringstream将int分配给字符串?

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

How do I assign an int to a string with stringstream ? 如何使用stringstreamint分配给string

The " stringstream(mystr2) << b; " doesn't assign b to mystr2 in the example below: 在以下示例中,“ 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;
}

This should do: 应该这样做:

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

This will print out the '10' correctly below. 这将在下面正确打印出“ 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;
}

When you create a string stream with the ctor stringstream(mystr2) the mystr2 is copied as the initial content of the buffer. 使用ctor stringstream(mystr2)创建字符串流时, stringstream(mystr2) mystr2复制为缓冲区的初始内容。 mystr2 is not modified by subsequent operations on the stream. 流上的后续操作不会修改mystr2

To get the content of the stream you can use the str method: 要获取流的内容,可以使用str方法:

int b = 10;
string mystr2;
stringstream ss = stringstream(mystr2);  
ss << b;
cout << mystr2.str() << endl; 

See constructor and str method. 请参见构造函数str方法。

The answer to your literal question is: 您的字面问题的答案是:

int b = 10;
std::string mystr2 = static_cast<stringstream &>(stringstream()<<b).str();
cout << mystr2 << endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM