Author Topic: C++: When reading for a char, how to stop paying attention after the first one  (Read 707 times)

Code: [Select]
#include <iostream>
#include <string>
using namespace std;

int main()
{
int ruinEverything = 0;

while(ruinEverything == 0)
{
char choice;
cout << endl << ">";
cin >> choice;
cout << endl;

switch(choice)
{
case 'a':
cout << endl << "You selected 'a'." << endl;
break;

case 'r':
cout << endl << "You selected 'r'." << endl;
break;

case 'n':
cout << endl << "You ruined everything.";
ruinEverything = 1;
break;

default:
cout << endl << "I'm not looking for '" << choice << "'.";
}
}
}



Instead of the above happening, how do I get it to look at 'a' and ignore anything else that was typed after it, or tell the user to only enter one character?



An alternate solution lies in figuring out how to read two words but no more than that.

i.e. "move north"

where "move" elicits "where do you want to move?"

"move nroth" elicits "I can't move nroth."

and "move north salad" elicits "what the forget stop it"

first you have to move north salad

I think you do cin.clear(); or something like that after the switch

i could be misinterpreting what you're saying, but how about don't keep looping into the switch after you've found a character?

i could be misinterpreting what you're saying, but how about don't keep looping into the switch after you've found a character?
I have to stay in the same location, ready for the next input immediately

I think you do cin.clear(); or something like that after the switch
it doesn't look like that changed anything
« Last Edit: November 03, 2012, 02:01:11 AM by Eksi »

GOT IT

thank you for vague guidance that led me to the answer mr. zombie foxface





Code: [Select]
int ruinEverything = 0;

while(ruinEverything == 0)
{
char choice;
cout << endl << ">";
cin >> choice;

switch(choice)
{
case 'a':
cout << endl << "You selected 'a'." << endl;
break;

case 'r':
cout << endl << "You selected 'r'." << endl;
break;

case 'n':
cout << endl << "You ruined everything.";
ruinEverything = 1;
break;

default:
cout << endl << "I'm not looking for '" << choice << "'." << endl;
}

cin.ignore(10000, '\n');    //Ignores everything up until when you hit Enter. perfect
}
« Last Edit: November 03, 2012, 02:22:52 AM by Eksi »