1

I'm basically trying to get the user's name (and I want them to be able to use spaces, which is why I have to use getline) and then the name of their fictional kingdom. But when I run this code, it skips ahead of itself. It asks for the name, but then it skips and asks for the kingdom name before even allowing the user to input their name. I've tried cin.ignore() but that doesn't work. Anybody have any suggestions?

string playerName = "nyd"; //declaring string playerName
string kingdomName = "nyd"; //declaring string countryName
int monarchAge; //declaring monarch age variable.

cout << "     Welcome, your majesty! What is your name?\n";
getline(cin,playerName);
cout << "     And what is the name of your grand kingdom, " << playerName << "?\n";
getline(cin,kingdomName);
cin.ignore();
cout << "     And finally, how old are you, Lord " << playerName << " of " << kingdomName << "?\n";
cin >> monarchAge;
Jacob Oaks
  • 140
  • 1
  • 11
  • 1
    Most likely http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction, and that call to `ignore` is most likely just eating the first character of the age. – chris Apr 18 '15 at 14:11
  • 1
    Why do you call `cin.ignore();` actually? – πάντα ῥεῖ Apr 18 '15 at 14:11
  • I read somewhere that cin.ignore() might help, so i tried it, guess not though – Jacob Oaks Apr 18 '15 at 14:12
  • @JacobOaks The hint you read somewhere about cin.ignore is for when you mix `cin >> v;` with `getline` this is because `operator>>(istream&, T)` usually ignores the newline at the end of the line. – Stian Svedenborg Apr 18 '15 at 14:26

1 Answers1

0

The snippet of code you supplied is actually correct. I get the expected behaviour when I compile it locally.

I still think I can tell you what is happening in your code. I assume the snippet you linked is only a part of your program, before the code that fails you most likely did a mistake. Something like trying to read a floating point number into an integer variable or similar. This will cause your stream (in this case cin) to be marked as bad.

Once a stream is marked as bad it will simply ignore all future calls to both getline() and operator>> untill cin.clear() has been called to reset the error flag.

So the fix would be, find out what makes your stream bad.

Stian Svedenborg
  • 1,607
  • 10
  • 26
  • Thank you so much! I never would of though it was a problem with my code earlier on in the program, which is now fixed and everything is working. Thanks! – Jacob Oaks Apr 18 '15 at 14:50