Thread: How do you verify the user input only numeric and not alpha letters or special chars?

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    5

    How do you verify the user input only numeric and not alpha letters or special chars?

    I have written a program that ask user the total amount of winning and losing hands in poker and then gives back his or her percentages.
    But I am having trouble with the do while loop. I am trying to get the do while loop to verify that the users only inputs numbers and if not then it should prompt the user again.
    The program works when you just put in numbers but it gives this output when you put in ANYthing else:

    **************************************************
    Note: The below stats could be for one continuous session of poker or for entire
    lifetime.
    Heads up, if you enter anything but a number you will be prompted to reenter.
    Please enter in the total number of hands the DEALER dealt: dfsa


    Please enter the total number of poker hands you got involved in preflop:
    Please enter the number of hands you have LOST:
    Please enter the number of hands you have WON:
    Total percentage of hands won out of 1.6978e-313 hands = 1.#INF


    Total percentage of hands lost out of 1.6978e-313 hands = 311237


    Press any key to continue . . .
    **************************************************

    Here is my code:
    Code:
    //Gordon Campbell Sept 2 2013
    //creating a program that uses a function to calculate poker win/loss percentages
    //I am having trouble with the do wile loop and the function it calls ie  "notnumber" function
    //trying to get the notnumber function in the do while loop to check the user input for characters,
    //if user inputs anything but numbers it should prompt user to reenter correct input :( 
    
    
    #include <iostream>
    using namespace std;
    
    
    double averageloss (double loss, double totalhands);                         //prototype for average losses
    double averagewin (double win, double totalhands);                           //prototype for average wins
    char notnumber (char alpha);                                                 //prototype for do while loop to verify user input is a number
    
    
    
    
    int main()
    {
    char alpha;                                                            //variable used in do while loop and function
    double loss;                                                           //variable used for hands lost
    double win;                                                            //variable used for hands won
    double involvedhands;                                                  //variable representing total hands usder got involved in preflop 
    double totaldealt;                                                     //wariable used for total hands DEALER dealt
    
    
    cout<<"Note: The below stats could be for one continuous session of poker or for entire lifetime."<<endl;
    cout<<"Heads up, through out this program, if you enter anything but a number you will be prompted to reenter."<<endl;                                                  
             do                                                            //supposed to check if user input is non alpha characters, but it does not work... boo
             {
             
             cout<<"Please enter in the total number of hands the DEALER dealt: ";
             
             cin>>totaldealt;
             cout<<" "<<endl;                                                    //use to produce a visual space before next cout statement
            
             }while(totaldealt == notnumber (alpha));                            
    
    
    
    
             
    cout<<"Please enter the total number of poker hands you got involved in preflop: "; 
    cin>>involvedhands;
    cout<<" "<<endl;                                                    //use to produce a visual space before next line
    cout<<"Please enter the number of hands you have LOST: ";
    cin>>loss;                                                          //passed into the averageloss function
    cout<<" "<<endl;                                                    //use to produce a visual space before next line
    cout<<"Please enter the number of hands you have WON: ";
    cin>>win;                                                           //passed into the averagewin function
    cout<<" "<<endl;                                                    //use to produce a visual space before next line
    
    
    cout<<"Total percentage of hands won out of "<<involvedhands<<" hands  = "<<averagewin(win, involvedhands) <<"\n"<<endl;    
        
    cout<<"Total percentage of hands lost out of "<<involvedhands<<" hands = "<<averageloss(loss, involvedhands) <<"\n"<<endl;
    system("PAUSE");
    }
    
    
    double averagewin(double win, double involvedhands)                //function definition for average wins
    {
    return win / involvedhands;   
        
    }
    
    
    double averageloss(double loss, double involvedhands)              //function definition for average losses
    {
    return loss / involvedhands;   
    }
    
    
    char notnumber(char alpha)                                         //function definition called in do while loop
    {
         alpha >= 'A' && alpha <= 'Z';
    return alpha;    
    }

    How do I write a loop that checks for correct numeric user input?
    It doesn't have to be a do while loop...
    I would appreciate any help in this manner.
    Thanks again,
    Gordon
    </code>

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Welcome in the forum. You can take a look into cctype.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  3. #3
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    Why are you using double type for storing natural numbers ?

    I'd use something like the following ..(add your error messages if you want to)
    Code:
    #include <iostream>
    
    template<typename T>
    T getNumber(std::istream& in)
    {
        T t;
        in>>t;
        if(in.fail())
        {
            in.clear();
            in.ignore();
            return getNumber<T>(in);
        }
        else return t;
    }
    int main()
    {
        std::cout<<getNumber<int>(std::cin);
    }

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    manasij7479's example would allow say, numeric input followed by trailing space on the line (but I note that you should read up on what the ignore member function does as you might encounter a problem concerning its use here). If this is acceptable to you, then well and good. If not, std10093's suggestion would point you in a right direction to read the input as a string and parse it manually. But if you want a solution along the lines of manasij7479's example, I suggest something like:
    Code:
    template<typename T>
    T getNumber(std::istream& in)
    {
        T result;
        std::string line;
        while (std::getline(in, line))
        {
            std::stringstream ss(line);
            if ((ss >> result) && ss.eof())
            {
                break;
            }
        }
        return result;
    }
    The idea here is to read line by line, turn the line into a stream, then read from the stream and check that the read succeeded. There is no need to worry about clearing the error state of the stream and getting rid of erroneous characters remaining in the stream since a new stream is created everytime you read the next line into the string.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    I generally do not get input line by line because I ran into a tricky bug with that a while ago.
    It was a 'competition' type problem, which just said that there would be N strings from the stdin.
    I assumed there would be N lines.
    It turned out that the examples on the site did, but their test suite lumped all the input together.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The bug was due to your misinterpretation of the requirements, not with reading line by line for interactive input.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Sep 2013
    Posts
    5

    Can I use C code along side my C++ code?

    Thanks Samaras for the libraries.
    I find this one (isalpha - C++ Reference) to be most useful for my purposes.
    But it is written in C primer. Can I use it as is in a C++ compiler with other C++ code?
    If not, I can swap the "printf" for cout and so on, but I may come across errors due to nuances from converting code from c to C++. Is there anything I should be aware of when translating C code to C++?
    I believe I remember my professors in college saying that C++ incorporates C, I guess my questions is can I use the code as is
    or (can) do I translate C++?
    Thanks for your help good sir/mam.

  8. #8
    Registered User
    Join Date
    Sep 2013
    Posts
    5
    Thank you for your help!

  9. #9
    Registered User
    Join Date
    Sep 2013
    Posts
    5
    This was really helpful.
    Thank you.

  10. #10
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    When including C headers, remove the .h at the end and prepend a 'c' before the name.
    (<ctype.h> becomes <cctype>)
    There are minor incompatibilities, but you are safe with using the C standard library...other than for memory allocation.

  11. #11
    Registered User
    Join Date
    Sep 2013
    Posts
    5
    Oh, Awesome. Thanks dude! Now I can carry on.

    Thanks again.

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Gordon Campbell View Post
    Thanks Samaras for the libraries.
    I find this one (isalpha - C++ Reference) to be most useful for my purposes.
    But it is written in C primer. Can I use it as is in a C++ compiler with other C++ code?
    If not, I can swap the "printf" for cout and so on, but I may come across errors due to nuances from converting code from c to C++. Is there anything I should be aware of when translating C code to C++?
    I believe I remember my professors in college saying that C++ incorporates C, I guess my questions is can I use the code as is
    or (can) do I translate C++?
    Thanks for your help good sir/mam.
    As mana says, C++ is backwards compatible with C, but there are some incompatibilities (such as C++ requiring as explicit cast when going from type void* to any other type).
    However, you should be aware that if you intend to write C++, then you really should start from the beginning and learning the language properly. C++ is not C with classes, although you can use it for that purpose if you have specific requirements/restrictions/time limits.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to check if a string is alpha numeric. D:
    By johnjrgs in forum C Programming
    Replies: 8
    Last Post: 02-20-2013, 06:25 PM
  2. alpha-numeric to numeric program
    By johnhuge in forum C Programming
    Replies: 2
    Last Post: 03-24-2012, 12:08 AM
  3. Replies: 10
    Last Post: 06-10-2010, 09:52 PM
  4. special chars
    By j_spinto in forum C Programming
    Replies: 8
    Last Post: 06-28-2005, 12:34 PM
  5. putting a numeric value into an array of chars?
    By ftsf in forum C++ Programming
    Replies: 2
    Last Post: 11-23-2002, 02:27 AM