Thread: Need Help

  1. #16
    Registered User
    Join Date
    Apr 2006
    Posts
    18
    In a menu code as the following:

    Code:
    void menu()
    {
    	char opcao;
      	
    	do
    	{
    		1- Insert
                    2- Alter
                    3- Search
                    4- Delete
                    5- Add
                    6- Multiply
                    7- XML
                    8- Sort
                    9- List
                    0- Exit
             
    		cout<<"Option:  ";
    		cin>>Option;
    		
    		
    		switch(Option)
    		{
    			case  '1' : insert(); break;
    			case  '2' : alter();break;
    			case  '3' : search(); break;
    			case  '4' : delete();break;
    			case  '5' : add();break;
    			case  '6' : multily();break;
    			case  '7' : xml();break;
    			case  '8' : sort(); break;
    			case  '9' : list(); break;
                            default   : "...":break;
    			
    			case  '0' : exit(0); break; 
    			
    		}
    
    	}while(opcao >='0' && opcao <='9' );
    
    }
    How can i prevent the user from inserting, for instance 148, and prevent the switch to execute the 1 ,4 and 8 options at the "same time" instead of blocking the number inserted because it is out of the 0-9 range ?

    Thanks

  2. #17
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    If you want to read 148 as an error, you could read it in as an integer instead of a char, and then use integers instead of characters in your switch.

    Or you could check to see if there are any other characters in the input stream and indicate an error if there are. One way to do that is to compare the result of cin.get() to '\n' after you read in the opcode. If the user only typed in the '1' and hit enter, it will be equal. If the user typed in anything after the '1' before hitting enter, then it will be not equal.

    In those situations you will want to ignore all the remaining characters in the input stream up to the actual newline from when the user did hit enter. To ignore all of them up to 1000, use cin.ignore(1000, '\n'). To ignore the maximum possible characters the user will be able to enter, #include <limits> and use cin.ignore(numeric_limits<streamsize>::max(), '\n');.

  3. #18
    Registered User
    Join Date
    Apr 2006
    Posts
    18
    Great!!


    It worked just fine.

    Thanks


Popular pages Recent additions subscribe to a feed