?
Solved

extract input from keyboard

Posted on 2003-03-20
13
Medium Priority
?
211 Views
Last Modified: 2010-04-01
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
0
Comment
Question by:wahdouglaslai
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +4
13 Comments
 
LVL 11

Accepted Solution

by:
fanopoe earned 672 total points
ID: 8174555
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
 
LVL 5

Expert Comment

by:Kocil
ID: 8174970
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
 
LVL 4

Expert Comment

by:n_fortynine
ID: 8175438
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Expert Comment

by:n_fortynine
ID: 8175441
500 points is an awful lot of points. =)
0
 
LVL 9

Expert Comment

by:Joeisanerd
ID: 8176842
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
 

Expert Comment

by:Cuperous
ID: 8178283
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
 
LVL 30

Assisted Solution

by:Mayank S
Mayank S earned 664 total points
ID: 8179438
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
 

Expert Comment

by:Cuperous
ID: 8184941
Mayank --
  But, what if the user enters any other letter besides 'd' or 'D' like 'k'?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8185658
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
 
LVL 5

Assisted Solution

by:Kocil
Kocil earned 664 total points
ID: 8188145
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
 
LVL 9

Expert Comment

by:tinchos
ID: 9510747
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
 
LVL 30

Expert Comment

by:Mayank S
ID: 9513720
Split between Kocil and mayankeagle.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 9513825
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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question