简体   繁体   中英

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. 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.

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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