extract input from keyboard

Experts

Suppose I have a program in C++ that need to obtain user's choice such as following:

Please select:
a. open account;
b. update account;
c. delete account;
x. exit

Please select (a, b, c or x then press enter):

My question is how can I ask user to re-enter selection if s/he accidently press enter key in stead of any one of the choice key?

The system should remind the user to re-select such as "It is not a choice please re-select: ". Also what function should be used? I tried to use such as "cin.get(selection)" but cannot get rid of the newline character that is created by pressing the enter key after selected a, b, c or d.

Best regard.

Chi
wahdouglaslaiAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

fanopoeCommented:
Try this:

char chrChoice; //Your input variable

do              //Do at least one time
{
    [display menu options]; //write your display code here
    cin >> chrChoice;  //accept the response

}while((chrChoice!='a')&&(chrChoice!='b')&&(chrChoice!='c')&&(chrChoice!='x')); //compare the response to the list

I usually add an int variable that counts the user's attempts to get it right and exits after x number of cosecutive failures. Also, this is only good if they enter lower case letters. If you want to accept upper and lower case you may want to try adding this:
chrChoice = tolower(chrChoice);
after the cin >> chrChoice; statement.

This code uses iostream and string libraries.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
KocilCommented:
Why don't you use the old fashioned C ? It's more convenient bacause you don't have to press ENTER to select the menu.

Menu()
  char chrChoice;
  do              //Do at least one time
  {
     //write your display code here

     chrChoice = getche();  // echo the typing
     // chrChoice = getch();  // no echo

     switch (chrChoice) {
      'a' : doOpen(); break;
      'b' : doUpdate(); break;
      'c' : doDelete(); break;
      'x' : return;
      default
         cout << "please re-select";
   }
}

0
n_fortynineCommented:
Kocil, the problem is with not using "old fashioned C" is
>>I have a program in C++
j/k =)

btw, wahdouglaslai, if you want minimal checking then just use cin, i believe cin a char ignores all preceding '\n's.
the problem you had with cin.get() leaving '\n' behind could be resolved by ignore().
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

n_fortynineCommented:
500 points is an awful lot of points. =)
0
JoeisanerdCommented:
If you keep you code as it is with the cin.get(selection) and compare it just make sure you make a call to flush(stdin) to flush any other characters.

Use

flush(stdin);
cin.get(selection);
flush(stdin);
0
CuperousCommented:
I hope this is helpful.

#include <conio.h>  //this class is for the getch() function
#include <iostream.h>

void main()
{
cout<<"Please select:\n";
cout<<"a. open account\n";
cout<<"b. update account\n";
cout<<"c. delete account\n";
cout<<"x. exit\n";
char ch;
ch=getch();   // This gets one character from the keyboard and puts it into the ch character
while(ch!='a'||ch!='b'||ch!='c'||ch!='z') //This loop checks to see if the character entered is one of the characters you wanted!
     {
     cout<<"That was an invalid choice, please select one of the following:\n";
     cout<<"a. open account\n";
     cout<<"b. update account\n";
     cout<<"c. delete account\n";
     cout<<"x. exit\n";
     ch=getch();
     }
cout<<ch;
}
0
Mayank SAssociate Director - Product EngineeringCommented:
Well, well.... 500 points and everyone's had a go at it! Ok, everybody deserves a chance. Let me have mine!

Since you don't want to go through the trouble of pressing 'Enter' after entering a character, so you can use getche () to read the character. It will also display the character on the screen so that you can see what character you entered (in case you entered an invalid one).

..
..
char choice ;

do
{
  cout << "\n\t Please select: \n\t ~~~~~~~~~~~~~~ "
       << "\n a. Open Account. "
       << "\n b. Update Account. "
       << "\n c. Delete Account. "
       << "\n d. Exit. "
       << "\n\t Enter choice: " ;
  fflush ( stdin ) ; // clear the input buffer - might be needed in some cases
  choice = getche () ;
 
  switch ( choice )
  {
    // the user might type the character in upper or lower case
    case 'a': // no 'break' statement here
    case 'A': // do your thing for opening an account
              break ;
    case 'b': // no 'break' statement here
    case 'B': // do your thing for updating an account
              break ;
    case 'c': // no 'break' statement here
    case 'C': // do your thing for deleting an account
              break ;
    case 'd': // no 'break' statement here
    case 'D': break ;

    default: cout << "\n\t Wrong choice! " ;

  } // end switch

} while ( choice != 'd' && choice != 'D' ) ; // end do-while


You will need to include <conio.h> for the getche () function and <stdio.h> for the fflush () function.

This loop will go on as long as the user doesn't type 'd' or 'D' and it will also not require you to press 'Enter' after every character.

Hope that helps!

Mayank.
0
CuperousCommented:
Mayank --
  But, what if the user enters any other letter besides 'd' or 'D' like 'k'?
0
Mayank SAssociate Director - Product EngineeringCommented:
Simple.... it'll go into the default statement and print "Wrong Choice! ". And since 'k' is not equal to 'd'and not equal to 'D', the do-while loop will run again and display the menu.

Mayank.
0
KocilCommented:
IMHO, cin and cout contains too much annoying thing (like flush, unflexible format, etc).
Real programmer will choose <stdio.h>,
except the teacher said you have to use <stream>.


0
tinchosCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Please Review

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer
0
Mayank SAssociate Director - Product EngineeringCommented:
Split between Kocil and mayankeagle.
0
Mayank SAssociate Director - Product EngineeringCommented:
I agree that he insists on solving the problem using stdio.h and not iostream, but that is also allowed in C++, since its a super-set of C. What matters is - the method should be right.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.