sscanf problems

This is a discussion on sscanf problems within the C Programming forums, part of the General Programming Boards category; I have made a program to accept integers only however if i put a 25e in it it still works ...

  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,211
    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,211
    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,006
    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,211
    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, 03: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-11-2003, 12:47 AM
  4. sscanf (I think)
    By RyeDunn in forum C Programming
    Replies: 7
    Last Post: 07-31-2002, 09:46 AM
  5. SSCANF help
    By mattz in forum C Programming
    Replies: 7
    Last Post: 12-10-2001, 04:53 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21