Click here to Skip to main content
15,894,540 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hey guys, I'm really new to C++ and I'm trying to figure out how to validate a char var--to see if it's an int between 1 and 6, basically. The program I have so far catches all the exceptions I want it to except for numbers over 9 and negative numbers.
When the number entered is 9 or higher it somehow (through the magic of ASCII, I guess) selects whatever the first number is (ie. 10 = Maimi, 122 = Miami, 25 = Denver, 220 = Denver, etc). Negative numbers act the same way (ideally it should allow for no negative numbers). I looked in my book and on the web but I found nothing.
Does my program suck...yes, do I feel like a retard for asking...yes. Please help! Thanks in advance.

conditions:

Must re-prompt user for input if the input isn't an int from 1 to 6
Must catch non-integer input



using namespace std;
void ShowMenu();
int main(int argc, char *argv[])
{
      char choice;
      int ch;
      int go = 1;
      ShowMenu();           
     
      while (go == 1)   //while and if loops to detect exceptions
      {
            cout<<"enter a choice: ";
            cin>>choice;
            
            if (!isdigit(choice))
            {
               cout<< "Enter an integer! \n";
               continue;
            } 
               
                  int ch = choice - '0'; //changes "char choice" to "int ch"
                  
                  if (ch >6 || ch <1)
                  {
                     cout<< "Enter a number between 1 and 6! \n";
                     continue;
                  }                  
                  if (ch <= 6 && ch >= 1)
                  {
                      go = go - 1;
                      
        switch(ch)   //the choices I want to limit the user to
        {
        case 1:   cout<<"You selected Miami. \n";
                  break;
        case 2:   cout<<"You selected Denver. \n";
                  break;
        case 3:   cout<<"You selected New York. \n";
                  break;
        case 4:   cout<<"You selected Buffalo. \n";
                  break;
        case 5:   cout<<"You selected Los Angles. \n";
                  break;
        case 6:   cout<<"Exiting program... \n";
                  break;                                      
        }
                      
                      
                  }
               }                      
                                                                                                                         
                    
    system("PAUSE");
    return EXIT_SUCCESS;
}       
    void ShowMenu()  //shows the menu
    {
     cout<<"Please select a destination by selecting a number, or enter 6 to exit: \n"
           "1) Miami   2) Denver  3) New York \n"
           "4) Buffalo 5) Los Angles 6) Exit Program \n";      
    }
Posted
Updated 8-Feb-11 10:56am
v5
Comments
Sergey Alexandrovich Kryukov 8-Feb-11 16:20pm    
Where is "catches all errors"? (You catch exceptions, not errors!) What's the problem, anyway? (Yes, it sucks, now what's the problem?)
--SA
thomas struss 8-Feb-11 16:27pm    
Fine then, I want to catch the exceptions. Is that better? The problem is that it won't catch EXCEPTIONS like: the number being two digit, and the number being negative.

The easiest way is to change your input to int. After that life will be a whole lot easier

MIDL
int myInt;
myInt = atoi (choice);



SEE Cplusplus[^] and MSDN[^] for details
 
Share this answer
 
v2
Comments
thomas struss 8-Feb-11 16:41pm    
If I do that can I still catch non-digit characters? Is there something like "isdigit" for int?
Yusuf 8-Feb-11 16:49pm    
You bet:
http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

Try Google, I am sure you will be amazed as to what you will find
thomas struss 8-Feb-11 17:30pm    
Cool, I'll try it out, thanks.
There's a simple C++ idiom you can use to read an object of any type with an extraction operator and check to see if it's been read successfully. It's only a couple of lines:

int n = 0;

if( std::cin >> n )
{
    std::cout << "I've read a number, it's a " << n << std::endl;
}
else
{
    std::cout << "Ooops, whatever you typed it wasn't a number..." << std::endl;

    std::cin.clear();
    std::string junk_line;
    std::getline( std::cin, junk_line );
}


The important bit is the line that does the read. It relies on two things:

- extraction operators return the stream they're operating on after the operation, this allows you to string extractions together.

- stream objects have a conversion operator to bool [1]. If this is false the stream is jammed up for some reason, usually because a conversion has failed or because the stream has hit an end of file condition. [2]

So when you do the read the one of the following things happen:

- the next characters out of the stream can represent an integer. Yay! The stream is in a good state and the condition is true.

- the next characters out of the stream can't represent an integer. Boo! The stream is clagged up and can't be read from until the error state is cleared. To do that you clear the stream state and then read and discard the line that's caused the problem - which the block of code after the error message.

Anyway, I hope this helps you write C++ that looks like C++ and not the slightly wonky C you've ended up using. If you're interested in C++ streams then I'd recommend reading "Standard C++ IOStreams and locales: Advanced programmer's guide and reference" By Angelika Langer and Klaus Kreft. It's a dry but informative read that will tell you everything you want to know about streams and loads more you don't.

Cheers,

Ash

[1] Actually it's not straight to bool, it's to a type of function pointer which is convertible to bool. Don't worry about details like that for now though.

[2] Again, this aint the whole story but enough to get you through your current problem.
 
Share this answer
 
I ended up going away from the "cin" route; I would still like to know if it's possible though.


C#
char choice[10];
   int intchoice, len;
   int go = 1;
   ShowMenu();
   while (go == 1)
   {
   printf ("Enter a choice: ");
   fgets (choice, 10, stdin);
   len = strlen (choice) -1;
   if (len > 1)
   {
      cout<< "Enter a choice below...only one number. \n";
      continue;
   }
   intchoice = atoi(choice);
      if (intchoice >6 || intchoice <1)
      {
          cout<<"Enter a choice between 1 and 6! \n";
          continue;
      }
      go = go -1;
   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900