简体   繁体   English

如何使用stringstream对象将整数多次转换为字符串?

[英]How to convert an integer to string multiple times using stringstream object?

I want to take an input as a integer and then concatenate it with a string. 我想将输入作为整数,然后将其与字符串连接。 This will be for multiple times. 这将是多次。 The output will be the previous string with this new integer value. 输出将是具有此新整数值的前一个字符串。 After taking input of an integer number I used stringstream object for converting it. 输入整数后,我使用stringstream对象对其进行了转换。 Then I concatenate it. 然后,我将其连接起来。 But I've got expected output for the first time. 但是我第一次获得了预期的输出。 But the next time when I take input from the user and try to concatenate it with the previous string output string in the concatenated part is the same of my first input integer. 但是,下一次我从用户那里获取输入并尝试将其与连接部分中的上一个字符串输出字符串连接时,与我的第一个输入整数相同。 So how can I use this stringstream object for further use. 因此,如何使用此stringstream对象进一步使用。

Here is my code: 这是我的代码:

string s = "Previous Choices :   ";
    int n;
    string d;
    stringstream ss;
    while(1) {
        cin>>n;
        ss << n;
        ss >> d;
        s += d;
        cout<<s<<”   ”<<endl;
}

My inputs 我的输入

10
20
30

My expected output is 我的预期输出是

Previous Choices :   10
Previous Choices :   10 20
Previous Choices :   10 20 30

But the output is coming like this: 但是输出是这样的:

Previous Choices :   10
Previous Choices :   10 10
Previous Choices :   10 10 10

Your did not clear your stringstream object for further use. 您没有清除stringstream对象以供进一步使用。 That is why it is containing the first input value and adding this for all of your inputs. 这就是为什么它包含第一个输入值并将其添加到所有输入中的原因。

So to clear this object you just add the following this code 因此,要清除该对象,您只需添加以下代码

ss.clear();

Then your code will be like this 然后您的代码将像这样

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();
}

I did something like this: 我做了这样的事情:

#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;
}

It works as You expected. 它按您预期的那样工作。

You can do it much more simply, without the intermediates s and d , directly using the stream as your accumulator. 您可以更简单地完成此操作,而无需中间sd ,而直接使用流作为累加器。

#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;
}

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

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