Search code examples
c++istringstream

How to get two integers separated by space in a char[]?


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.


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