Thread: Input Validation!

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    3

    Input Validation!

    Hello everyone.

    Right, it's a simple setup for my program, it reads in a number (as an int) and then does something with it. But, as everyones probably noticed if you type in a character the program 'crashes'. I have the following code:

    Code:
    #include <stdio.h> 
    
    void main()
    {
      int temp;
      printf ("Input your number: ");
      while (scanf("%d", &temp) != 1)
      {
         while (getchar() != '\n');
        printf ("Try again: ");
      }
      printf ("You entered %d\n", temp);
    }
    but I don't understand what the return value from scanf and the new line character have to do with checking for a letter! Is there an easier way of doing this? (I usually use fgets to get an input). Any help with this would be greatly appreciated.

    Cheers,
    Chris.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > but I don't understand what the return value from scanf
    scanf() returns the number of conversions AND assignments.
    Since a letter fails a conversion to int, scanff() will return 0 in that case

    > and the new line character
    That's to throw away all the characters which scanf() failed to use. Since you don't know how many (or what they are), you have to go with one you can reasonably expect to find - and thats a newline

    > I usually use fgets to get an input
    Yeah - fgets() and sscanf() is far superior in this case.

    Oh, and main returns an int.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2004
    Posts
    3
    cheers salem! i understand whats actually happening now!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Printing Length of Input and the Limited Input
    By dnguyen1022 in forum C Programming
    Replies: 33
    Last Post: 11-29-2008, 04:13 PM
  2. Problem getting the input from a temp variable into the Array
    By hello_moto in forum C++ Programming
    Replies: 3
    Last Post: 03-16-2006, 01:50 AM
  3. Input validation loop failure
    By MacNilly in forum C++ Programming
    Replies: 4
    Last Post: 03-01-2006, 03:29 AM
  4. Input Validation Question
    By zackboll in forum C Programming
    Replies: 14
    Last Post: 10-12-2004, 12:05 AM
  5. need help with some input
    By blindleaf in forum C Programming
    Replies: 2
    Last Post: 03-16-2003, 01:50 PM