1

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.

Shane Hsu
  • 7,937
  • 6
  • 39
  • 63

3 Answers3

4

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);
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • I've been suspecting that for a while. I used to use a for loop looking for the space. And each time, it fails. I can't find any reference in my book that says cin will ignore a whitespace. But now I know. Thank you very much. It will fix a lot of my problems. – Shane Hsu Sep 10 '11 at 04:56
  • @Shane: To clarify, it's not just cin, it's *all* istreams. And it's not always, it's only when using `operator>>`. Istreams have other input functions which don't do that. `getline` like I showed you, but also `read`, `get` and some others. – Benjamin Lindley Sep 10 '11 at 05:10
  • `istream`s can also be instructed to *preserve* whitespace with the `noskipws` manipulator, and whitespace can then be explicitly captured and ignored with the `ws` manipulator. – greyfade Sep 10 '11 at 05:50
  • Thanks for all the replies. greyfade and Benjamin Lindley. – Shane Hsu Sep 10 '11 at 06:54
1

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);
Martin York
  • 257,169
  • 86
  • 333
  • 562
1

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);
JohnPS
  • 2,518
  • 19
  • 17