Thread: error checking problem with scanf

  1. #1
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335

    error checking problem with scanf

    I have the following code:

    Code:
    #include<stdio.h>
    
    int main()
    {
        FILE *fp;
        char name[25];
        char buff[BUFSIZ];
        float num;
    
        if((fp=fopen("test.txt","r"))==NULL)
        {
            perror("File cannot be opened");
            getchar();
            exit(1);
        }
    
        while(fgets(buff,sizeof(buff),fp)!=NULL)  // read a single line from the file till i get EOF
        {
            if(sscanf(buff,"%s %f",name,&num)==2)  // getting the name and the number from the  buffer which was read from the file
            printf("%s %.1f\n",name,num);
            else
    
            printf("line cannot be printed\n");
        }
    
        getchar();
        return 0;
    }

    and test.txt:

    Elsewhere 22.65 11.95
    Overthere 55
    Sidknee 147 34


    Since "55" isn't a valid double, i don't want to print any of the records. What's happening now is:

    Sarah 22.65 11.95
    line cannot be printed
    Sandy 147.00 34.00

    Is there anyway when theres a int found to exit and print nothing but an error message?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Then read your 'double' into another string variable (like you do with name), then use say strtod() and perhaps strchr() to make sure it meets your rather exact definition of a double.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with RPC and scanf
    By Ricardo_R5 in forum C Programming
    Replies: 11
    Last Post: 01-08-2007, 06:15 PM
  2. Problem with scanf float..
    By aydin1 in forum C Programming
    Replies: 6
    Last Post: 03-06-2005, 01:35 PM
  3. scanf problem
    By gsoft in forum C Programming
    Replies: 3
    Last Post: 01-05-2005, 12:42 AM
  4. problem with looping scanf
    By crag2804 in forum C Programming
    Replies: 6
    Last Post: 09-12-2002, 08:10 PM
  5. scanf problem
    By Flikm in forum C Programming
    Replies: 2
    Last Post: 11-05-2001, 01:48 PM