Reputation: 823
I have a program that asks the user to enter input several times, and stores that input in different char variables, and then does things to those variables.
My problem is that I want to restrict the input to work for one variable at a time. For example:
char a = 'a', b = 'b', c = 'c';
cout << "Enter a ";
cin >> a;
cout << "\nEnter b ";
cin >> b;
cout << "\nEnter c ";
cin >> c;
cout << "Entered chars were " << a << ", " << b << ", " << c;
Running this, if the user enters t y u (including the spaces between the letters) will make the program to enter t into variable a, y into variable b, and u into variable c. Essentially, it would sort of "fall through" and automatically put values for cin rather than asking the user to do it for each one.
What I want, is to check that what the user enters for variable a is 1 char only.
I have tried using cin.good(), however it returns a 0 after entering more than one character for cin >> a; I have also tried using cin.get(a); and then checking for cin.good(). This also returns 0 if user enters more than one character.
Is there a way to restrict the input to work for only one cin operation at a time?
Upvotes: 3
Views: 24671
Reputation: 108
From C language . You can use getch(); which take only one char at a time .
If you want to multiple characters , i mean string . you use getch(); with in loop. getch() is from conio.h and getche() also available to display on console.
Upvotes: 3
Reputation: 132994
You should read your input line by line and then parse it. As such
std::cout << "Enter a:\n";
std::string input;
std::getline(std::cin, input);
if(input.length() != 1)
//error
else
char a = input[0];
Upvotes: 10