Thread: sscanf problems

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    27

    Question sscanf problems

    I have made a program to accept integers only however if i put a 25e in it it still works how do i fix it?

    Code:
    char line[MAXLINE];
    int error, n;
    
    do
    {
        printf("Input a positive integer:   ");
        fgets(line, MAXLINE, stdin);
        error = sscanf(line, "%d", &n) != 1 || n <= 0;
        if(error)
            printf("\nERROR: Do it again. \n");
     }while (error);

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Use strtol(). It will show you if any extra non-digit characters were in the buffer.

  3. #3
    Registered User
    Join Date
    May 2007
    Posts
    27
    i have to use sscanf and i am not familiar with this

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Then I believe you have to manually check variable line yourself and see if it contains any non-digit chars.

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  6. #6
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Or that. Nice solution.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sscanf matching problems
    By KBriggs in forum C Programming
    Replies: 10
    Last Post: 06-23-2009, 02:20 PM
  2. sscanf()
    By task in forum C Programming
    Replies: 4
    Last Post: 11-22-2003, 04:43 PM
  3. Simple sscanf mystery
    By registering in forum C Programming
    Replies: 4
    Last Post: 06-10-2003, 11:47 PM
  4. sscanf (I think)
    By RyeDunn in forum C Programming
    Replies: 7
    Last Post: 07-31-2002, 08:46 AM
  5. SSCANF help
    By mattz in forum C Programming
    Replies: 7
    Last Post: 12-10-2001, 04:53 PM