That code can bomb for a number of reasons.
All user input should be
carefully validated. As a beginner, it is easiest if you just get all user input with
std::
getline() and use, if necessary, an
istringstream to get some thing(s) out of it.
If you want to skip that, then you must be sure to properly synchronize the user's input to what you expect next.
The iostream
sync() method isn't actually required to do anything, which makes it useless (and it actually is useless on many systems). Alas.
But that is a digression. For your (
Arcand's) stated problem, I have to wonder why you are not using the
std::
string class with
std::
getline() to get user input? This will simplify your life considerably.
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 27 28 29 30 31
|
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string users_input;
cout << "> ";
while (getline( cin, users_input ))
{
// Convert the user's input to lowercase
transform(
users_input.begin(),
users_input.end(),
users_input.begin(),
(int(*)(int)) std::tolower
);
// Act based upon the user's input
if (users_input == "quit") break;
else if (users_input == "hello") cout << "Greetings Earthling!\n";
else if (users_input == "bye") cout << "Oh, no! Don't tell me to quit!\n";
else cout << "What?\n";
cout << "> ";
}
cout << "Well, goodbye then.\n";
return 0;
}
|
> hello
Greetings Earthling
> what's up
What?
> HELLO
Greetings Earthling
> bye
Oh, no! Don't tell me to quit!
> good bye!
What?
> quit
Well, goodbye then. |
Foo. Silly example, but hopefully helpful.