Thread: Data Format Error Detection.

  1. #1
    Registered User
    Join Date
    Jan 2004

    Data Format Error Detection.

    Hi, all this is my first post in this forum. I am really new with this stuff.

    Ok what i need to do is this, when entering the data i need the Variable to accept only integers and not characters. if a user enters a character it will re prompt for the data.

    printf("Please Enter the number of Sales People :");
    scanf("%d", &num);
    i want it so that the variable 'num' only accepts integers if the user enters a letter it will re prompt wiht the same message.

  2. #2
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Ontario, Canada
    Don't use scanf( ). Search the board to find out why.

    Then, you can just check the return value of sscanf( ).
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >scanf("%d", &num);
    Always check the return value of interactive input functions. If you must use scanf, you can write something sufficiently ugly to do what you want:
    while ( scanf ( "%d", &num ) != 1 ) {
      int ch;
      if ( ferror ( stdin ) ) {
        perror ( "Read error" );
        exit ( EXIT_FAILURE );
      fprintf ( stderr, "Invalid input, try again: " );
      while ( ( ch = getchar() ) != '\n' && ch != EOF )
    Of course, a better solution would be to use fgets to read an entire line of input and then parse it, usually with sscanf.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about a working linked list
    By cold_dog in forum C++ Programming
    Replies: 23
    Last Post: 09-13-2006, 01:00 AM
  2. Binary Tree, couple questions
    By scoobasean in forum C Programming
    Replies: 3
    Last Post: 03-12-2005, 09:09 PM
  3. HUGE fps jump
    By DavidP in forum Game Programming
    Replies: 23
    Last Post: 07-01-2004, 10:36 AM
  4. C diamonds and perls :)
    By Carlos in forum A Brief History of
    Replies: 7
    Last Post: 05-16-2003, 10:19 PM
  5. C Programming Question
    By TK in forum A Brief History of
    Replies: 13
    Last Post: 07-04-2002, 07:11 PM