Asking for an int and I get letters

This is a discussion on Asking for an int and I get letters within the C++ Programming forums, part of the General Programming Boards category; If I want the user to enter an integer (int) and they enter a letter, the screen fills up with ...

  1. #1
    Um...well...
    Guest

    Asking for an int and I get letters

    If I want the user to enter an integer (int) and they enter a letter, the screen fills up with a buncha repeats. Like...

    Code:
    int Age;
    cout<< "Enter your age: ";
    cin>> Age;
    If they entered 'Hello' in, it would crash the program, displaying 'Enter your age:' forever. How do I get around this? Any help would be nice, big time!

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    A good solution is usually to read the input into a string and then call a function which validates that string. This way you can define the behavior for valid and invalid input and you don't have to rely on cin, which is annoying at best. Here's a somewhat naive implementation of that method:
    Code:
    #include <iostream>
    #include <string>
    #include <cctype>
    
    bool validate ( std::string &chk )
    {
      int i;
      for ( i = 0; i < chk.length(); i++ )
        if ( !isdigit ( chk[i] ) )
          return false;
      return true;
    }
    
    int main()
    {
      std::string input;
      std::getline ( std::cin, input );
      if ( validate ( input ) )
        std::cout<<"Everybody is happy!\n";
      else
        std::cout<<"Bugger, invalid input.\n";
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  3. #3
    Um...well...
    Guest

    Talking Alright then!

    Thank you Prelude, you are a very smart (wo)man. Now I don't have to worry about crashing my entire program when I accidently enter a letter.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21