Wait, what was the question again?
If you're wondering why this works:
Enter a command: give sword
Give which item?:
Enter a command: view
sword
---
---
---
---
---
---
---
---
---
Enter a command: exit |
Here's what happens:
1. Program asks you to enter a command. Say you enter "give sword".
2. Program reads in "give", stopping at the space character (
cin >> something
always stops when it sees a whitespace character).
3. Program asks you to enter an item. There's already " sword" in the input buffer, so
cin doesn't need to get anything from the user and just reads in "sword". (the space character at the beginning is ignored)
(That's a pretty simplified explanation, I'll admit, but it's close enough....)
If you want to read a whole line of text (including spaces and all), use
1 2
|
string input;
getline(cin, input);
|
(I think someone already mentioned that)
Oh, and @EssGeEich:
That's not really a "bug".
It's supposed to do that...what else would you expect it to do?
Anyways, you can always do (well, assuming
cin.sync() does its job properly, which usually you don't have to worry about it):
1 2 3 4 5 6 7
|
int num;
while (!(cin >> num))
{
cin.clear(); // Clear the error flag
cin.sync(); // Clear out all the junk in the buffer
cout << "Grr, why'd you do that?!\nTry again: ";
}
|
(or use strings and stringstreams)