scanf() usage

This is a discussion on scanf() usage within the C Programming forums, part of the General Programming Boards category; This program was basically a problem in an exam. "A text file contains a list of real numbers separated by ...

  1. #1
    Registered User slash.hack's Avatar
    Join Date
    Sep 2011
    Posts
    21

    scanf() usage

    This program was basically a problem in an exam.

    "A text file contains a list of real numbers separated by comma. Write to read the real numbers from the given text file and determine average of the numbers from the list of real numbers."

    I used this code to generate the numbers as required.
    Code:
    #include<stdio.h>
    #include<conio.h>
    int main()
    {
         FILE *fptr;
         fptr =  fopen ("numbers.txt","w");
         if(fptr == NULL)
         {
                 printf("Error reading the file.");
         }
         fprintf(fptr,"1,2,3,4,5,6,7,8");
         fclose(fptr);
         getch();
    }
    This is what I coded to get the job done.
    Code:
    #include<stdio.h>
    #include<conio.h>
    int main()
    {
         FILE *fptr;
         fptr =  fopen ("numbers.txt","r");
         if(fptr == NULL)
         {
                 printf("Error reading the file.");
         }
         int count = 0, sum=0, num = 0, i,n;
         while((fscanf(fptr,"%d,",&n))!=EOF)
         {
                      count = count + 1;
                      sum = sum + n;
                      printf("check... \n"); //just to do a loop check
         }fclose(fptr);
         printf("The average of the given numbers are %d",sum/count);
         getch();
    }
    Well, the program did its task. But before I got to this, I used
    while((fscanf(fptr,"%d",&n))!=EOF)
    [without the comma inside the quotes, i.e. "%d"]

    This cause the program to loop over and over which can easily be tracked by the "check..."

    I wanted to know how this difference occured.

    Plus, I'd love to get suggestions regarding my programming style and alternative solutions to this problem, if it isnt much to ask.
    Thank you.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    > while((fscanf(fptr,"%d,",&n))!=EOF)
    Well checking for == 1 would be a more positive test than != EOF
    Another answer you could have gotten from fscanf() was 0 (no conversion), and this is what happens when the format of the file breaks down.

    As for style,
    1. don't put code after closing braces.
    2. avoid using conio.h and getch - neither of which are portable.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You could use the return value of fscanf() differently. Eg:

    Code:
    int n, check;
    char skip[8];
    check = fscanf(fptr, "%d%7[^0-9]", &n, skip");
    The second item is anything non-numeric, but a maximum of 7 characters. Presuming there is not excessive garbage in the file, that will get you past commas, spaces, newlines, etc. You could use %*[^0-9] to discard this item, but by using the "skip" buffer instead, you should get a return value from fscanf of 2 as long as there is more data to read, <=0 when there is none, and 1 for the last number (if there is no additional commas, whitespace, newlines, et. al.).

    That might be more reliable that using EOF.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User slash.hack's Avatar
    Join Date
    Sep 2011
    Posts
    21
    Well, I wanted the loop to end if it read EOF, after reading your reply it seems, fscanf just returns either 1 or 0.
    If you dont mind, can you modify the code so that this can be achieved using fread instead of fscanf?
    Thank you very much for replying ^^

    edit: @MK27 I read your post just after I posted this. Wow, this is a lot advanced form of code. (kinda difficult to understand, I'll check the usage, am a n00b ) So fscanf returns the number of variables that it was associated with?
    Last edited by slash.hack; 09-15-2011 at 08:17 AM.

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    No, the scanf() family of functions return the number of items successfully scanned or a negative number indicating EOF or error. That's why I said if you have two items, you will get either 2, 1, or <=0. It's better to test for success rather than EOF, because that is what counts.

    Using a combination of fread() and sscanf() or strtok() is good if the file is small enough to slurp all at once, or has some kind of persistent chunked structure. But you'll have to try some code yourself, I won't write it for you.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #6
    Registered User slash.hack's Avatar
    Join Date
    Sep 2011
    Posts
    21
    MK27 is there any site or resource that I learn about functions such as scanf() in more detail, as you have used above?

  7. #7
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Quote Originally Posted by slash.hack View Post
    MK27 is there any site or resource that I learn about functions such as scanf() in more detail, as you have used above?
    There is:
    Of course you could always look through the C book recommendations and select a good book, such as K&R.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  8. #8
    Registered User slash.hack's Avatar
    Join Date
    Sep 2011
    Posts
    21
    Thank you so much for the links. I found something while looking up for advanced format modifiers, upon analyzing tutorial documentation I found that it was meant for language called Pike 7.0 but it seems pretty identical to sscanf usage as in C. This might help those who were looking up regarding format specifiers.

    Hoping if this is valid for this thread
    Analyzing Strings with sscanf

    Found another, very useful this one :
    http://beej.us/guide/bgc/output/html...age/scanf.html
    Last edited by slash.hack; 09-15-2011 at 10:43 AM. Reason: Added a link

  9. #9
    Registered User slash.hack's Avatar
    Join Date
    Sep 2011
    Posts
    21
    This worked too!
    I replaced while((fscanf(fptr,"%d,",&n))!=EOF) in the above code by : while((fscanf(fptr, "%d%*[^0-9]",&n)) == 1)
    "%*" The * says throw away what is read, don't store it in an output variable, this was quoted from here.

    Sorry about the double post. lol

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by slash.hack View Post
    MK27 is there any site or resource that I learn about functions such as scanf() in more detail, as you have used above?
    The very best source of information on your C Library functions usually comes from your compiler's own documentation. The really good ones include the Libary Documentation in the download (or on the disk)... Second to that you can visit the compiler's home page and most often there will be help files, man pages, or pdf files with the documentation you can download. You should favor this because it is specific to your compiler, it's libraries and their various quicks and kinks...

    Don't mistake this for an option. Any programming project bigger than "Hello World" is going to dog-ear the printouts in no time flat. Any function you are not familiar with should be looked up before use... and with literally hundreds of functions in the average library only a fool would try to memorize it. Of course this gets worse when you venture into an OS's Application Programming Interface (API) where tens of thousands of functions is very typical.

    On a "best guess" basis, I'd say that an average programmer spends about 1/3 of his writing time "looking stuff up"...
    So if you don't have this documentation you really do need to find it and get copies of it on your system.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. do {} 13% CPU usage ?!?!?!?
    By military genius in forum C++ Programming
    Replies: 9
    Last Post: 10-13-2009, 08:57 PM
  2. VC++ 6 - CPU Usage Help
    By solem1 in forum C Programming
    Replies: 0
    Last Post: 09-08-2009, 11:16 PM
  3. First scanf() skips next scanf() !
    By grahampatten in forum C Programming
    Replies: 5
    Last Post: 08-17-2004, 02:47 AM
  4. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM
  5. Usage
    By whistlenm1 in forum C++ Programming
    Replies: 9
    Last Post: 07-10-2002, 11:06 AM

Tags for this Thread


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