Thread: accepting char and int

  1. #1
    Unregistered
    Guest

    accepting char and int

    Hey everyone I have this problem with the menu to a game I'm programming.... I want a loop that will not screw up when I put something other than a number in it.... heres the code I used.


    do

    {

    int character;

    cout<<"1. Paladin\n";
    cout<<"2. Warrior\n";
    cout<<"3. Rogue\n";
    cout<<"4. Mage\n";

    cin>>character;

    }while((character!=1) || (character!=2) || (character!=3) || (character!=4))


    Problem is when I input a letter or anything other than a number it goes into an infinate loop where it wont let me enter any data, it simple keeps looping the text! How can I make it when I put in something other than a number that it simple goes through the menu agian and allows me to enter text instead of scrolling the damn menu over and over and over agian. This is driving me mad someone please help!

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    two main categories of data validation are always input data as a string, then validate string AND use the istream methods called good() or fail() and combine either with clear(). Either method works. You could even try reading in with scanf() rather than an istream, but I think that has it's own set of hassles.

  3. #3
    A Banana Yoshi's Avatar
    Join Date
    Oct 2001
    Posts
    859

    ignore() function will work

    Use char instead because if you enter a character, it will go crazy.

    and also, the (character != 1 || ... ) part is not right, you enter any number it will still go into that loop again because it did not satisify all the demands:
    if you entered '1', the comp will process: (character!= '1' || ...) ok pass, but when it goes into the second one (...||character !='2'...) it does not satisify this so it will go back to that loop.

    Solution make every "||" into "&&"

    Hope this will help
    Yoshi

  4. #4
    Unregistered
    Guest
    That first post made absolutely no sense to me... I need some example code of it

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. NEED HELP READING FILE and PRINTING
    By geoffr0 in forum C Programming
    Replies: 4
    Last Post: 04-16-2009, 05:26 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  4. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  5. Replies: 4
    Last Post: 11-23-2003, 07:15 AM