getline messes up program

simple program I'm trying to expand a little. But when it loops around, it combines the sentences and messes the progam. I not sure how to make the loop stay the same after the first round.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
using namespace std;

int main ()
{

  string mystr;
  string x = "yes";

while ( x == "yes" ) {

  cout << "What's your name? ";
  getline (cin, mystr);
  cout << "Hello " << mystr << ".\n";
  cout << "What is your favorite team? ";
  getline (cin, mystr);
  cout << "I like " << mystr << " too!\n";

  cout << "Do you want to play again?" << endl;
  cin >> x;
}
 return 0;
}

That's because cin >> x; leaves the newline character (from you pressing the Enter key) in the input stream, and getline eats that character instead of waiting for more input.

You have a few options here.
1) Since x is also a string, change cin >> x; to getline(cin, x);.

2) Put a cin.ignore(); after your cin >> x; statement. This will only work if you don't type ANYTHING more than one word (so, for instance, it won't work if you type "yes I do" at the "Do you want to play again?" prompt).

3) Put something like cin.ignore(80, '\n'); after cin >> x;. (It doesn't have to be 80 -- you can just make up some sufficiently large number or something)
This'll work for inputs like "yes I do" (it'll eat the " I do\n"), but it won't work if you type something like "yes please please please let me play again I love this game wheeeeeeeeeeeeeeeeeeee!" (I think that's more than 80 characters).

4) #include <limits> , and put cin.ignore(numeric_limits<streamsize>::max(), '\n'); after cin >> x;. Then it'll work regardless of whatever garbage you might think to type at the prompt.
(This is probably the best solution other than #1, by the way)

5) Umm...maybe a cin.sync(); after cin >> x; might work? (I'm not sure what the story behind that is)
Topic archived. No new replies allowed.