如何使用 stringstream 对象多次将整数转换为字符串?
How to convert an integer to string multiple times using stringstream object?
我想将一个输入作为一个整数,然后将它与一个字符串连接起来。这将是多次。输出将是具有此新整数值的先前字符串。输入整数后,我使用 stringstream
对象进行转换。然后我连接它。但是我第一次得到了预期的输出。但是下次当我从用户那里获取输入并尝试将其与前一个字符串连接时,连接部分中的输出字符串与我的第一个输入整数相同。那么我该如何使用这个 stringstream
对象以供进一步使用。
这是我的代码:
string s = "Previous Choices : ";
int n;
string d;
stringstream ss;
while(1) {
cin>>n;
ss << n;
ss >> d;
s += d;
cout<<s<<” ”<<endl;
}
我的输入
10
20
30
我的预期输出是
Previous Choices : 10
Previous Choices : 10 20
Previous Choices : 10 20 30
但是输出是这样的:
Previous Choices : 10
Previous Choices : 10 10
Previous Choices : 10 10 10
您没有清除您的字符串流对象以供进一步使用。这就是为什么它包含第一个输入值并将其添加到您的所有输入中。
因此,要清除此对象,您只需添加以下代码
ss.clear();
那么你的代码就是这样的
string s = "Previous Choices : ";
int n;
string d;
stringstream ss;
while(1) {
cin>>n;
ss << n;
ss >> d;
s += d;
cout<<s<<” ”<<endl;
ss.clear();
}
我做了这样的事情:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string s = "Previous Choices : ";
int n;
stringstream ss;
while(1)
{
cin >> n;
ss << n;
//cout << "in ss stream is: " << ss.str() << endl;
s = s + ss.str() + " ";
cout << s << endl;
ss.str(string());
}
return 0;
}
如您所愿。
你可以更简单地做到这一点,没有中间体 s
和 d
,直接使用流作为你的累加器。
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream ss;
ss << "Previous Choices : ";
while(1)
{
int n;
cin >> n;
ss << n;
cout << ss.str() << endl;
}
return 0;
}
我想将一个输入作为一个整数,然后将它与一个字符串连接起来。这将是多次。输出将是具有此新整数值的先前字符串。输入整数后,我使用 stringstream
对象进行转换。然后我连接它。但是我第一次得到了预期的输出。但是下次当我从用户那里获取输入并尝试将其与前一个字符串连接时,连接部分中的输出字符串与我的第一个输入整数相同。那么我该如何使用这个 stringstream
对象以供进一步使用。
这是我的代码:
string s = "Previous Choices : ";
int n;
string d;
stringstream ss;
while(1) {
cin>>n;
ss << n;
ss >> d;
s += d;
cout<<s<<” ”<<endl;
}
我的输入
10
20
30
我的预期输出是
Previous Choices : 10
Previous Choices : 10 20
Previous Choices : 10 20 30
但是输出是这样的:
Previous Choices : 10
Previous Choices : 10 10
Previous Choices : 10 10 10
您没有清除您的字符串流对象以供进一步使用。这就是为什么它包含第一个输入值并将其添加到您的所有输入中。
因此,要清除此对象,您只需添加以下代码
ss.clear();
那么你的代码就是这样的
string s = "Previous Choices : ";
int n;
string d;
stringstream ss;
while(1) {
cin>>n;
ss << n;
ss >> d;
s += d;
cout<<s<<” ”<<endl;
ss.clear();
}
我做了这样的事情:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string s = "Previous Choices : ";
int n;
stringstream ss;
while(1)
{
cin >> n;
ss << n;
//cout << "in ss stream is: " << ss.str() << endl;
s = s + ss.str() + " ";
cout << s << endl;
ss.str(string());
}
return 0;
}
如您所愿。
你可以更简单地做到这一点,没有中间体 s
和 d
,直接使用流作为你的累加器。
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream ss;
ss << "Previous Choices : ";
while(1)
{
int n;
cin >> n;
ss << n;
cout << ss.str() << endl;
}
return 0;
}