Question

I will be getting a string of numbers that looks like this.

12 45

Two integers separated with space.

The output will be 57.

I have tried using,

string numbersstream;
cin >> numbersstream;
istringstram twonumbers (numbersstream);
twonumbers >> a >> b;

But each time I run it, only a is correct, b isn't.

What other functions is there to help me? Or is this just a coding problem I have?

I got two kinds of suggestions already in the answers.

getline(cin,numbersstream);

And

cin << a << b;

Thank you all for your time. Additional methods will be very appreciated.

Was it helpful?

Solution

The problem is with your input from cin. Using operator>> is whitespace delimited. So if the user types "12 45", only the 12 will be extracted. You could use getline instead:

getline(cin,numbersstream);

OTHER TIPS

Try this:

int main()
{
    int a;
    int b;

    std::cin >> a >> b;
    std::cout << a+b << "\n";
}

The problem is that in your code:

cin >> numbersstream;

Only reads one space separated word (ie 12) into the string numbersstream. Thus when you build twonumbers it actually only has one number in it. Hence it only sets 'a' and 'b' is left undefined.

You could do it your way but what you really need here is to read the whole line into the string:

std::getline(std::cin, numbersstream);
istringstram twonumbers (numbersstream);

You are only reading until the first whitespace character with

cin >> numberstream;

The following will read everything into the string until a delimiter character is read ('\n') or end-of-file. The delimiter is discarded.

getline(cin,numbersstream);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top