Thread: validating user input

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    4

    Question validating user input

    im writing a programing C++ it gets numbers from the users ive forgotten how to validate the user entry so if a character is entered the user is asked to re enter the number i know a do loop can be used i just require the condition

  2. #2
    Just a Member ammar's Avatar
    Join Date
    Jun 2002
    Posts
    953
    You can use cin.goo(), this function returns a bool, so you can check it an if statement

  3. #3
    Seeking motivation... endo's Avatar
    Join Date
    May 2002
    Posts
    537
    He means cin.good( )

    Couldn't think of anything interesting, cool or funny - sorry.

  4. #4
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    cin.good() has drawbacks. As long as the input begins with a digit, cin.good() will return "true", truncating the first invalid character and anything that follows. That is, '25g9j' will be held as '25'. Not too good. (Pardon the pun. )

    This has been suggested before (by Prelude, if not others). Place your input into a string and validate the individual characters. On success, convert the string to a numeric value.

    Not quite as bad as it seems.
    Code:
    #include <iostream>
    #include <cstdlib>  // system call
    #include <ctype>    // isdigit()
    #include <cmath>    // atof (ASCII to float (double) )
    #include <iomanip>  // setprecision()
    
    inline void pause() { system("PAUSE"); }
    
    int main(void)
    {
    char* input = " ";
    double numVal;
    bool valid = true;
    
    std::cout << "Enter a numeric value: -> ";
    std::cin >> input;
    
        for ( unsigned int i = 0; i < strlen(input); i++ ){
    
            if ( !isdigit(input[i]) && input[i] != '.'){
    
                std::cerr << "\nError! " << "\'" << input[i] << "\'"
                          << " is an invalid character.\n\n";
                valid = false;
            }
        }
    
        if ( valid ){
            numVal = atof(input);
            std::cout << setiosflags(std::ios::fixed)<< std::setprecision(2)
                      << "\nnumVal = " << numVal << "\n\n";
        }
    
    pause();
    return 0;
    }
    I don't attest to the elegance of my approach here, but it works. Note that I've written the code using 'atof' vice 'atoi'. It can be easily modified to suit your particular needs.

    -Skipper
    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

  5. #5
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    You might want to allocate some space for the input, too.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  6. #6
    Registered User
    Join Date
    Sep 2002
    Posts
    272
    >That is, '25g9j' will be held as '25'. Not too good.

    Unless that was required. Using good/fail/etc in this way allows simple parsing of strings. Besides, if you want to alter it's behaviour you could do something like -

    Code:
    #include <iostream>
    
    using std::cin;
    using std::cout;
    
    int main()
    {
    	double numVal;
    	
    	cin >> numVal;
    	while(cin.fail())
    	{
    		cin.clear();
    		cin.ignore();
    		cin >> numVal;
    	}
    	
    	//Ensure everthing on line is valid
    	if(cin.get()!='\n')
    		cout << "Input invalid\n";
    	else
    		cout << numVal;
    	
    	return 0;
    }
    If you needed to include other delimeters (' ') the code would be straightforward.
    Joe

  7. #7
    Just a Member ammar's Avatar
    Join Date
    Jun 2002
    Posts
    953
    He means cin.good( )
    Thanks, I was on a harry.

    I like what skipper wrote.

    by the way is cin.good() == !cin.fail()
    I mean is there any differences between them

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I mean is there any differences between them
    Yes, fail() tests only the failbit for the stream state, good() tests badbit, eofbit, and failbit and will return true only if none of them are set.

    -Prelude
    My best code is written with the delete key.

  9. #9
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    > Yes, fail() tests only the failbit for the stream state, good() tests badbit, eofbit, and failbit and will return true only if none of them are set.
    Doesn't fail() also test badbit?

    (Sorry, just happened to be revising my code to account for multiple decimal points when I noticed your post. )

    -Skipper
    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Doesn't fail() also test badbit?
    Yes, I should stop posting in a hurry, it hurts my reputation.

    -Prelude
    My best code is written with the delete key.

  11. #11
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    Nah, it's still intact.

    -Skipper
    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  3. Structure and Linked List User Input Question
    By kevndale79 in forum C Programming
    Replies: 16
    Last Post: 10-05-2006, 11:09 AM
  4. Nested Structures - User Input
    By shazg2000 in forum C Programming
    Replies: 2
    Last Post: 01-09-2005, 10:53 AM
  5. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM