preventing error

Hi!

I'm currently writing a small program in C++ for my programmingclass, and I've got a problem:

The user is prompted for a number between 1 and 44. If he (or she) do so the program does what it is made for. If he writes a too small, negative or too large number, the user gets an error message and is prompted for a new number. This works fine BUT if the user types a letter the program freaks out. How can I prevent this?

I hope someone can help me......


//// David - Sweden

Comments

  • : Hi!
    :
    : I'm currently writing a small program in C++ for my programmingclass, and I've got a problem:
    :
    : The user is prompted for a number between 1 and 44. If he (or she) do so the program does what it is made for. If he writes a too small, negative or too large number, the user gets an error message and is prompted for a new number. This works fine BUT if the user types a letter the program freaks out. How can I prevent this?
    :
    : I hope someone can help me......
    :
    :
    : //// David - Sweden
    :
    [blue]You need to get a string from the user, not the number. Use [b]atoi()[/b] to convert it and then [b]if()[/b] to test the 1-44 condition.[/blue]
  • : : Hi!
    : :
    : : I'm currently writing a small program in C++ for my programmingclass, and I've got a problem:
    : :
    : : The user is prompted for a number between 1 and 44. If he (or she) do so the program does what it is made for. If he writes a too small, negative or too large number, the user gets an error message and is prompted for a new number. This works fine BUT if the user types a letter the program freaks out. How can I prevent this?
    : :
    : : I hope someone can help me......
    : :
    : :
    : : //// David - Sweden
    : :
    : [blue]You need to get a string from the user, not the number. Use [b]atoi()[/b] to convert it and then [b]if()[/b] to test the 1-44 condition.[/blue]
    :

    Or if you are using iostreams which you should and probably are, then when the stream reads in invalid input the stream goes to a bad state where all further reads fail. You can reset it to a good state with cin.clear().

    For example,

    int x;
    cin>>x;
    //user types 'a'
    //cin.good()==false now
    if(!cin.good()){
    cin.clear();
    print error message
    }


    "We can't do nothing and think someone else will make it right."
    -Kyoto Now, Bad Religion

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories