Thread: Checking user input?

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    14

    Checking user input?

    Hey all.

    What is the simplest way to check whether a user has inputted an integer and not a character?

    Thankyou in advance for any help!
    Colin.

  2. #2
    Registered User
    Join Date
    Apr 2005
    Posts
    12
    could try to use isdigit()

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    14
    cheers... How does that function work and waht does it test for....

    I need a function that will check whether the user has inputted an integer number (i.e. not a character) and repeat the input if a non integer is inputted...

  4. #4
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int main(int argc, char** argv)
    {
            unsigned char input = 0;
    
            printf("Input a number:\n");
    
            do {
                    scanf("%c",&input);
            }
            while (!isdigit(input));
    
            printf("\nYou entered: %c\n",input);
    
            return 0;
    }
    isdigit() takes an integer or unsigned char value as an argument. It tests whether the argument is a decimal digit, returning a non-zero if true or 0 if false.

  5. #5
    Registered User
    Join Date
    Mar 2005
    Posts
    14
    Sorry i don't really understand the code used above... i have a pretty limited knowledge...

    The code where the user inputs needs to be checked is as follows

    code:
    Code:
    /*User input section... User inputs coefficients*/
    printf("Please enter the coefficients of the polynomial:\n");
    printf("p=");
    scanf("%f", &p);
    printf("q=");
    scanf("%f", &q);
    printf("r=");
    scanf("%f", &r);
    I need a function that checks whether the user inputs an integer value in each case as the valuse are used in later calculations... Appologies for being inspecific earlier.

  6. #6
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    I was just demonstrating the use of the isdigit() function from the ctype library. What you want is to have a loop (I'm assuming you have done loops before) that keeps looping until all 3 inputs in your case (p, q and r) are all digits. i.e. Returns true (non-zero) from the isdigit() function.

    Here's some code to help you out a bit since you are a bit stuck:

    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int main(int argc, char** argv)
    {
            int ch;
            unsigned char p = 0, q = 0;
            int num_times = 0;
    
            printf("Input: ");
    
            do {
    
                    if (num_times > 0)
                            printf("Please try again. Only integers are allowed!\n");
    
                    printf("p=");
                    scanf("%c",&p);
    
                    /* Clears the input buffer */
                    while ( (ch = getchar()) != '\n' && ch != EOF);
    
                    printf("q=");
                    scanf("%c",&q);
    
                    /* Again clears the input buffer */
                    while ( (ch = getchar()) != '\n' && ch != EOF);
    
                    num_times++;
            }
            while (!(isdigit(p) && isdigit(q)));
    
            printf("\nYou entered: %c %c\n",p, q);
    
            return 0;
    }
    The two commented while() loops are used to clear the input buffer from the effects of the newline when you use scanf(). Basically what happens is that if you have:
    Code:
    printf("p=");
    scanf("%c",&p);
    The user would enter an integer and press return (enter key). The integer is read in by the scanf() but the return (\n) is still in the input buffer. So if we didn't clear the buffer then the second scanf() in the example above will read in the newline from where we left the first scanf().

    The other code is pretty simple, the do... while construct has the condition for the loop to end both "p" and "q" must be integers - we use the isdigit() standard library function to validate this. If either one is not an integer then the loop will start back at where "do" is and will print the message: "Please try again..."

    Note I only used 2 variables (p and q), it's up to you to understand and code in the 3rd variable. Theres not much point of me coding it all for you since you won't learn much

  7. #7
    former member Brain Cell's Avatar
    Join Date
    Feb 2004
    Posts
    472
    or you could try this : http://www.mashhoor.ws/bpc.html#five

    put the validation code in a sperate function instead of typing it after each input.
    My Tutorials :
    - Bad programming practices in : C
    - C\C++ Tips
    (constrcutive criticism is very welcome)


    - Brain Cell

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You could also just read the FAQ entry on getting a number from a user.

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Dec 2004
    Posts
    12
    Try this code. I think this should work (although a bit modification is needed).

    Code:
     
    /*
      Code to get the coefficients for a polynomial function.
      Code by : just_A_student
    */
    
    #include <stdio.h>
    
    int main(void)
    {
      int p = 0, q = 0, r = 0, iInput = 0, iNext = 1;
    
      printf("\n Enter the coefficients of p, q, and r : \n");
    
      while((iInput = getchar()) != EOF)
      {
        /* what if the input contains whhitespaces ? move on to the
            next coefficients ! */
    
        if(iInput == ' ' || iInput == '\n' || iInput == '\t')
        {
            if(iNext == 3)
               break;
            ++iNext;
            fflush(stdin);
        }
    
        else
        {
            if(iInput < '0' || iInput > '9')  /* means input is not a number*/
            {
               printf("\n Please enter a number : ");
               fflush(stdin);
            }
    
           else
           {
               if(iNext == 1)
    	         p = (p * 10) + (iInput - '0');
               if(iNext == 2)
    	         q = (q * 10) + (iInput - '0');
               if(iNext == 3)
    	         r = (r * 10) + (iInput - '0');
           }
         }
      }
    
      printf("\n The coefficients are \n p = %d\n q = %d and\n r = %d",p,q,r);
      printf("\n Press any key to continue...");
      getch();
      exit(0);
    }

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Haven't you already been told not to use fflush( stdin )? If not, you're being told so now. Here's a FAQ entry telling you why.

    Furthermore, the FAQ entry I already mentioned shows better ways of getting a number from a user.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to limit user input to a certain number of digits?
    By NewbGuy in forum C Programming
    Replies: 7
    Last Post: 05-08-2009, 09:57 PM
  2. timed user input
    By sainiabhishek in forum C Programming
    Replies: 4
    Last Post: 04-01-2009, 11:59 AM
  3. Truncating user input
    By CS_Student8337 in forum C Programming
    Replies: 10
    Last Post: 03-19-2009, 12:34 AM
  4. Replies: 4
    Last Post: 04-21-2004, 04:18 PM
  5. checking user input for "type"
    By itld in forum C++ Programming
    Replies: 1
    Last Post: 12-24-2001, 05:25 AM