Thread: Validate User input(How to make sure it's not a character)

  1. #1
    Registered User
    Join Date
    Feb 2015
    Posts
    83

    Validate User input(How to make sure it's not a character)

    I got the program to ensure that it only accepts the numbers one and two. What do i put to make sure the user can't put in a character.
    Code:
    // Fig. 3.10: fig03_10.c
    // Analysis of examination results.
    #include<stdio.h>
    
    // Function main begins program execution
    int main(void)
    {
            // intialize variable in definitions
            unsigned int passes = 0; // number of passes
            unsigned int failures = 0; // number of failures
            unsigned int student = 1; // student counter
            int result; // one exam result
    
    // process 10 students using counter-controlled loop
            while(student <= 10) {
    
            // prompt user for input and obtain value from user
            printf("%s", "Enter result(1=pass, 2=fail):");
            scanf("%d", &result);
            if(result<1){
            printf("Invalid input\n");
            scanf("%d", &result);
            }
            if(result>2){
            printf("invalid input\n");
            scanf("%d", &result);
            }
            // if result 1, increment passes
            if (result ==1) {
            passes = passes + 1;
            }// end if
    
            else { // otherwise, increment failures
            failures = failures + 1;
            } // end else
    
            student = student + 1; // increment student counter
            }// end while
    
            // termination phase; display number of passes and failures
            printf("Passed %u\n", passes );
            printf("Failed %u\n", failures );
    
            // if more than eight passed, print "Bonus to instructor!"
            if (passes > 8) {
            puts("Bonus to instructor!");
    
            } // end if
            } // end function main

  2. #2
    Registered User
    Join Date
    Feb 2015
    Posts
    83
    The program will scan in a total of 10 students, you will input a 1 for pass and 2 for fail, the program will then show you how many students passed and how many failed. If more then 8 students passed it will put bonus to the instructor.

    I have already got it to accept only the numbers 1 and 2, how do i make sure a letter can't be input

  3. #3
    Registered User
    Join Date
    Apr 2015
    Location
    Bangalore, Karnataka, India
    Posts
    34
    Quote Originally Posted by ashley1nonly View Post
    What do i put to make sure the user can't put in a character.
    You can check the return value of scanf() to make sure everything went well.

    If scanf() has returned 0 then there may be a problem (may be you have asked for int but user has entered a char) then you should print something to convey the user of the misuse and clean the buffer by calling fpurge() or fflush() something else before going to accept the next input.

    The code may be something like this:

    Code:
    while (scanf("%d", &result) == 0) {
        printf ("Please enter an int.\n");
        fpurge();
    }

  4. #4
    Registered User
    Join Date
    Feb 2015
    Posts
    83
    can i also use that statement to help compress my code for example
    Code:
    while(scanf("%d", &results) ==0 || <1 || >2){
    printf("please enter a valid input(1 or 2)\n");
    fpurge();
    }

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by www.infysim.org
    If scanf() has returned 0 then there may be a problem (may be you have asked for int but user has entered a char) then you should print something to convey the user of the misuse
    scanf might also return EOF if there is a read error before the first conversion was completed, so merely checking if it does or does not return 0 is insufficient. As such, it tends to be better to check for the number of expected conversions rather than for 0 or EOF.

    Quote Originally Posted by www.infysim.org
    clean the buffer by calling fpurge() or fflush() something else before going to accept the next input.
    Yes, you should discard the invalid input that is in the input buffer. However, you should not use fpurge or fflush unless you are absolutely sure that you are willing to be tied to a non-standard implementation: fpurge is non-standard, not even POSIX standard, and fflush is undefined for input streams.
    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

  6. #6
    Registered User
    Join Date
    Feb 2015
    Posts
    83
    Code:
    #include<stdio.h>
    
    // Function main begins program execution
    int main(void)
    {
            // intialize variable in definitions
            unsigned int passes = 0; // number of passes
            unsigned int failures = 0; // number of failures
            unsigned int student = 1; // student counter
            int result, temp; // one exam result
    
    // process 10 students using counter-controlled loop
            while(student <= 10) {
    
            // prompt user for input and obtain value from user
            printf("%s", "Enter result(1=pass, 2=fail):");
            scanf("%d", &result);
            if(result<1){
            printf("Invalid input...please enter a 1 or 2\n");
            scanf("%d", &result);
            }
            if(result>2){
            printf("invalid input...please enter a 1 or 2\n");
            scanf("%d", &result);
            }
    if(result=0){
    printf("invalid input...please enter a 1 or 2\n");
    scanf("%d", &result);
    }
            // if result 1, increment passes
            if (result ==1) {
            passes = passes + 1;
            }// end if
    
            else { // otherwise, increment failures
            failures = failures + 1;
            } // end else
    
            student = student + 1; // increment student counter
            }// end while
    
            // termination phase; display number of passes and failures
            printf("Passed %u\n", passes );
            pr
            // if more than eight passed, print "Bonus to instructor!"
            if (passes > 8) {
            puts("Bonus to instructor!");
    
            } // end if
            } // end function main
    intf("Failed %u\n", failures );

    when i do it this way it say invalid input but then it goes directly to the EOF
    is there a simple one line while loop that i can use.
    I'm just trying to make sure the user can only put in a 1 or 2

    thanks to all in advance

  7. #7
    Registered User
    Join Date
    Feb 2015
    Posts
    83
    I can't use fpruge because i haven't got that far in my c programming class

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ashley1nonly
    can i also use that statement to help compress my code for example
    Possible, but you need to write your comparisons correctly, e.g.,
    Code:
    while (scanf("%d", &results) != 1 || results < 1 || results > 2) {
        int c;
        printf("please enter a valid input(1 or 2)\n");
        while ((c = getchar()) != '\n' && c != EOF);
    }
    EDIT:
    I noticed this line:
    Code:
    if(result=0){
    The above is a mistake because instead of comparing for 0, i.e., result == 0, you assigned 0.

    In general, you need to indent your code properly.
    Last edited by laserlight; 02-28-2016 at 01:37 PM.
    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

  9. #9
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Quote Originally Posted by www.infysim.org View Post
    Code:
    while (scanf("%d", &result) == 0) {
        printf ("Please enter an int.\n");
        fpurge();
    }
    It is recommended that instead of using fflush() or the non -standard fpurge() functions on input strings, it s better to use the following:
    Code:
    int ch = 0;
    while ((ch = getchar()) != '\n' && ch != EOF);
    EDIT:

    I said "input strings", but meant "input files".
    Last edited by rstanley; 02-28-2016 at 02:08 PM.

  10. #10
    Registered User
    Join Date
    Feb 2015
    Posts
    83
    Code:
    
    
            // prompt user for input and obtain value from user
            printf("%s", "Enter result(1=pass, 2=fail):");
            while(!(scanf("%d", &result) <1 || >2 || ch==getchar() ))
            {
            printf("Please enter valid int\n");
            scanf("%d", &result);
            }
    what about this while loop
    i state while scanf cannot be less than 1, greater than 2, or (==) to getchar
    Last edited by ashley1nonly; 02-28-2016 at 01:52 PM.

  11. #11
    Registered User
    Join Date
    Feb 2015
    Posts
    83
    Quote Originally Posted by rstanley View Post
    It is recommended that instead of using fflush() or the non -standard fpurge() functions on input strings, it s better to use the following:
    Code:
    int ch = 0;
    while ((ch = getchar()) != '\n' && ch != EOF);
    you program is saying
    while ch (which is an integer cannot equal getchar)
    cannot equal new line
    and cannot equal end of file

    is this correct


    so
    Code:
    while(!(scanf("%d", &result) <1 || >2){
           printf("please enter valid number\n");
           scanf("%d", &result)'
     while((ch = getchar()) != '\n' && ch != EOF){
        
     printf("please enter valid number\n");
           scanf("%d", &result);
    }

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ashley1nonly
    what about this while loop
    i state while scanf cannot be less than 1, greater than 2, or (==) to getchar
    You have wrong logic and invalid syntax:
    • scanf does not return the value that you are trying to read: it returns the number of conversions made or EOF, i.e., with "%d" as your format string, you expect one conversion to be made. Hence, !(scanf("%d", &result) is wrong: !EOF would be 1. This is why I wrote: scanf("%d", &results) != 1 || results < 1. The subexpression before the || compares with 1 because 1 conversion is expected; the subexpression after the || compares with 1 because that is the lower limit of the valid values of results.
    • >2 is simply invalid syntax. Notice that I wrote: results > 2
    • ch==getchar() is simply out of place. The logic does not make sense at all. The use of getchar() is to discard the invalid input, hence it should be in a loop within the body of the loop that reads with scanf. Your attempt to put it all in a single loop is misguided.
    • Since scanf is called within the loop condition, it should not also be called within the loop body to read into results.


    EDIT:
    Quote Originally Posted by ashley1nonly
    you program is saying
    while ch (which is an integer cannot equal getchar)
    cannot equal new line
    and cannot equal end of file
    Not quite. ch is an int because EOF is an int, and getchar can return EOF. We would read it more like: "assign the return value of getchar to ch, and if after the assignment ch is not equal to '\n', and if ch is not equal to EOF, keep looping".
    Last edited by laserlight; 02-28-2016 at 02:05 PM.
    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

  13. #13
    Registered User
    Join Date
    Feb 2015
    Posts
    83
    scanf("%d", &results) != 1

    so you wrote this because using %d i can only make one conversion(meaning that it will only check to see if the result is right once) and if it is not right it will go to the EOF

    trying to break down what you wrote step by step so i can get a full understanding.

  14. #14
    Registered User
    Join Date
    Feb 2015
    Posts
    83
    also when i use result=0
    i am storing the number zero at the integer location results
    vs.
    when i say result==0
    i am saying if result is equal to 0(meaning that i am comparing what is already stored in the integer zero location then comparing it to 0

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ashley1nonly
    scanf("%d", &results) != 1

    so you wrote this because using %d i can only make one conversion(meaning that it will only check to see if the result is right once) and if it is not right it will go to the EOF
    No. Contrast with this:
    Code:
    int x, y;
    while (scanf("%d%d", &x, &y) != 2) {
        /* ... */
    }
    Now, there are two %d conversion specifiers in the format string, hence two conversions are expected. If there is a read error, EOF would be returned; if there is a conversion error, 0 or 1 might be returned. If both conversions are successful, 2 will be returned, upon which the loop will terminate.
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 10-26-2013, 02:48 PM
  2. Validate user input
    By ulti-killer in forum C Programming
    Replies: 17
    Last Post: 07-12-2012, 11:09 PM
  3. Replies: 9
    Last Post: 06-16-2012, 09:18 AM
  4. Ending user input with # character
    By jowatkins in forum C++ Programming
    Replies: 2
    Last Post: 04-27-2004, 10:41 AM
  5. Validate a user input integer?
    By criticalerror in forum C++ Programming
    Replies: 20
    Last Post: 12-07-2003, 08:30 PM