std::cin misunderstanding

I expected this code would ask both: string and integer values, but it only asked for string value. What's wrong?

1
2
3
4
5
6
7
8
9
  string myString;
  int a = 0;
  int b = 0;

  cin >> myString;
  cout << myString << endl;

  cin >> a >> b;
  cout << a * b << endl;
My guess would be that you're entering a string that consists of more than one word. Using the formatted string extraction will result in only the first word being extracted and the subsequent stuff in the input buffer will cause line 8 to fail.
I don't know what causes that but the code works properly for me,
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main()
{
    string myString;
    int a = 0;
    int b = 0;
    cin >> myString;
    cout << myString << endl;
    cin >> a >> b;
    cout << a * b << endl;
    return 0;
}

The Output:

Gibs_Rey
Gibs_Rey
4
5
20

Process returned 0 (0x0)        execution time : 21.582 s
Press ENTER to continue.


I use g++ in Code:Blocks IDE
Last edited on
I don't know what causes that but the code works properly for me,

Try replacing that underscore with a space.
Try replacing that underscore with a space


What do you mean with that?
What do you mean with that?

I think it was suggested as a simple way to reproduce the problem experienced by the OP.
thanks, guys! I was entering more than one word.
Topic archived. No new replies allowed.