2

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

3 Answers 3

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.