#include<iostream>
using namespace std;
void fun() {
while(1) {
char choice;
cout<<"(D)isplay, (E)xit"<<endl;
start:
cout<<">> ";
cin>>choice;
switch(choice) {
case 'd':
case 'D':
cout<<"hello world"<<endl;
break;
case 'e':
case 'E':
return;
default:
cout<<"INVALID!"<<endl;
goto start;
}
}
}
int main() {
system("clear");
fun();
return 0;
}
This is a simple c program. I am faciing following problem:
(D)isplay, (E)xit
>> mnop
INVALID!
>> INVALID!
>> INVALID!
>> INVALID!
>>
The symbol '>>' prompt user to enter a character and with that it give apppropriate result but if entered a string it behaves something like this. I want to know why this happens and how to stop it :)
CodePudding user response:
Your code does what you told it to but not more: cin>>choice; reads a single character. When the user types more than a single character then the other characters are left in the stream and will be read by the next call.
If you want to handle input of more than a single character properly then you need to extract more than single character from the stream. For example:
while (true) {
std::string input;
std::cin >> input;
if (input.size() > 1 || input.size() == 0) {
std::cout << "enter only a single character\n";
} else {
choice = input[0];
break;
}
}
Alternatively you could check if there are more characters left in the stream after reading one and/or simply discard them (via ignore).
CodePudding user response:
Try calling cin.clear() after getting your value, and possibly also cin.ignore(INT_MAX). This will clear the buffer for you.
CodePudding user response:
cin >> choice , you are reading only one char. Remaining chars remain in buffer and read when you again call cin >> choice. Try string asdf then you will see output.
You can flush std in or simply read all remaining chars using cin.read();
basically clear input buffer by reading all chars.
CodePudding user response:
You are taking a character input from the user. Char means only one character so if you enter a string like "mnop", there are four characters in that. Each is considered as a separate input so you get "INVALID!" four times.
A solution can be to take a string input and check the length of that input first. If it is greater than 1 then ignore it else check whether if its 'D' or 'E'.
You can also use getch() function. It restricts the user to enter only one character.
#include <stdio.h>
#include <conio.h>
char ch = getch();
