Thread: sscanf help

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    4

    sscanf help

    I need help mofiying this code. As is right now, it will catch some typing errors. But if I type 54y it will not catch it. How can I modify this code so it will catch those type of errors?

    Code:
    #define MAXLINE 100
    
    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("\nDo it again!\n");
    } while(error)

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define MAXLINE 100
    
    int main(void)
    {
      char line[MAXLINE];
      int error, n, x;
    
      do{
        printf("Input a positive integer:  ");
        fgets(line, MAXLINE, stdin);
        error = sscanf(line, "%d%n", &n, &x) != 1
          || x < strlen(line) - 1
          || n <= 0;
        if(error)
          printf("\nDo it again!\n");
      } while(error);
    
      return 0;
    }
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Nov 2004
    Posts
    4
    Thanks Prelude!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sscanf and string handling question
    By ursula in forum C Programming
    Replies: 14
    Last Post: 05-30-2009, 02:21 AM
  2. Problem using sscanf fgets and overflow checking
    By jou00jou in forum C Programming
    Replies: 5
    Last Post: 02-18-2008, 06:42 AM
  3. Problems reading formatted input with sscanf
    By Nazgulled in forum C Programming
    Replies: 17
    Last Post: 05-10-2006, 12:46 AM
  4. sscanf question
    By Zarkhalar in forum C++ Programming
    Replies: 6
    Last Post: 08-03-2004, 07:52 PM
  5. sscanf (I think)
    By RyeDunn in forum C Programming
    Replies: 7
    Last Post: 07-31-2002, 08:46 AM