Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

extract input from keyboard

Posted on 2003-03-20
13
Medium Priority
?
213 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
  • 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

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Question has a verified solution.

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

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…
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

578 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