Thread: Why won't this simple statement work?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    120
    Thanks. So what would be the most simple/beginner way to not allow a character? Without using try catch or anything.

    I tried using something like
    Code:
    bool valid = true;
    if(isalpha(a)) valid = false;
    
    while(!valid)
    {
       cout << enter a num\n";
       cin >> a;
    }
    That won't work either. It gives me a crazy runtime error.

    The only reason i'm doing this is because someone who just started learning c++ asked me about this. It seemed really simple at first, but after playing around with the most basic ways I can think of, I cannot get it to work! What is the most simple way to handle a ?

  2. #2
    Banal internet user
    Join Date
    Aug 2002
    Posts
    1,380
    Code:
    #include <iostream>
    #include <limits>
    using namespace std;
    
    
    
    int main()
    {
        int a;
        cout << "Enter number\n";
    
        while (!(cin >> a))
        {
            cout << "number only\n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),'\n');
        }
    }
    If the stream formatter can't make the necessary type conversion then the stream goes into the fail state and the data in the buffer remains, thus to "start over" you have to clear() the fail state, then empty out the buffer, which you can do by calling ignore(), it ignores the maximum stream size number of characters or until it reaches the delimiter (EOL in this case)
    Last edited by BMJ; 10-18-2010 at 09:38 PM.

  3. #3
    Registered User Swarvy's Avatar
    Join Date
    Apr 2008
    Location
    United Kingdom
    Posts
    195
    I haven't tried this code so there are no guarantees, but on the face of it, this seems like a simple way of doing it. Although I wonder how it would hold up if you put in '>', '#', ';' or basically any other type of unusual symbol.

    Code:
    char a[BUFF_SIZE];
    int a_num;
    
    do
    {
           cout << enter a num\n";
           cin >> a;
    } while( isalpha(a) );
    
    a_num = (int)atof(a);
    Edit: BMJ's method is much cleaner. Use his. lol.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How properly inherit from template?
    By 6tr6tr in forum C++ Programming
    Replies: 118
    Last Post: 04-25-2008, 04:30 AM
  2. Simple program won't work on a friend's comp
    By Ouendanation in forum C++ Programming
    Replies: 6
    Last Post: 01-25-2008, 08:03 PM
  3. simple fread doesn't work
    By ronenk in forum C Programming
    Replies: 3
    Last Post: 10-15-2004, 05:08 AM
  4. string & if statement
    By Curacao in forum C++ Programming
    Replies: 4
    Last Post: 05-02-2003, 09:56 PM
  5. Replies: 1
    Last Post: 04-02-2003, 07:50 PM