3

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?

2
  • You can just call ignore to kill the rest of the input (slowly and painfully). Commented Mar 22, 2013 at 16:52
  • 1
    Use getline to get one line at a time. Discard any excess values on each line. Commented Mar 22, 2013 at 16:53

2 Answers 2

10

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];
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.