sscanf help

This is a discussion on sscanf help within the C Programming forums, part of the General Programming Boards category; I need help mofiying this code. As is right now, it will catch some typing errors. But if I type ...

  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,796
    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, 03: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, 01:46 AM
  4. sscanf question
    By Zarkhalar in forum C++ Programming
    Replies: 6
    Last Post: 08-03-2004, 08:52 PM
  5. sscanf (I think)
    By RyeDunn in forum C Programming
    Replies: 7
    Last Post: 07-31-2002, 09:46 AM

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