Thread: Scanning integers from a file:

  1. #1
    Raven
    Join Date
    Nov 2004
    Location
    Inside a Centrifuge
    Posts
    3

    Scanning integers from a file:

    Hello I need some help, I would like to scan integers from a text file that has both characters and integers.

    This is the text file:

    Peter Koffman 57 82 97
    Caryn Limonson 83 87 92
    George Siacoura 75 87 32
    Shirl Urys 95 72 88
    When I scan for integers, it scans the characters as well, and converts them into int >_________>. I try to do a caclulation (add the integers up) and end up with a number like this:
    45645267798


    Here's the statement I was using (note all variables have been defined):

    Code:
    FILE *in_fpt
    FILE *out_fpt
    
    fscanf(in_fpt, "%d%d%d", &scr1, &scr2, &scr3);
    Ovsiously that would not work, so I tried to do a while statement, here's the whole code.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    FILE *in_fpt, *out_fpt;             //fpt = file pointer//
    
    void copy_cat(FILE*, FILE*);        //will copy the information via strings//
    float avg_calc(FILE*);   //will calculate averages//
    
    
    main()
    {
        in_fpt = fopen("tests.txt", "r");
        out_fpt = fopen("copy_cat.txt", "w+");
        
        fprintf(out_fpt, "Names                  Scr 1   Scr 2   Scr 3      Average\n\n");    //heading//
        fprintf(out_fpt, "%d", avg_calc(in_fpt));
        
        
            
        fclose(in_fpt);
        fclose(out_fpt);
        
        
        return EXIT_SUCCESS;
    }
    
    
    /*
    void copy_cat(FILE *in_fpt, FILE *out_fpt)
    {
        char storage[99];
    }   
    */
    
    float avg_calc(FILE *in)
    {
        int scr1, scr2, scr3;      //scores on tests//
        int tot1, tot2, tot3;      //total score for test 1, 2, 3.//
        float scr_avg, tot_avg;    //average for each student, average for each test// 
        tot1=tot2=tot3=0;
    
        char test;    //tests for new line character and/or EOF//
    
        while( 0 < (test = fgetc(in)) < 9 ){ 
        /*check to see that the scanned character is 0<x<9 to make sure it is an int*/
                  
            fscanf(in, "%d %d %d", &scr1, &scr2, &scr2);
            scr_avg = (scr1 + scr2 + scr3);
            /*tot1 +=scr1;
            tot2 +=scr2;
            tot3 +=scr3;*/
    
            if( (test = fgetc(in)) == '\n'){        //exit statement when the line has ended//        
                break;
                else( 0 > (test = fgetc(in)) > 9){//force statment to run even if char is scanned//
                    continue;
                } //closes the else statment//  
            } //closes the if statment//    
       } //closes the while statement//
       return scr_avg;        
    }

    Im having problems compiling the above so anyaway, let me ask a more concrete question;

    Is there a way to test what data type has been aquired via scanf, as in that I scanned in an integer and not a character?

    That way I can created a condition while(scanf() = integer) do this and that.

    Thank you for the help.

  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
    Well using fscanf() is not my first choice.

    This is how you read each line from the text file
    Code:
    char buff[BUFSIZ];
    while ( fgets( buff, sizeof buff, in_fpt ) != NULL ) {
      /* do stuff with a line */
    }
    Having got a line, we can deal with it however we want, without having to worry about file errors or scanning errors.
    Since you mentioned fscanf(), we'll use sscanf()

    Code:
    char buff[BUFSIZ];
    while ( fgets( buff, sizeof buff, in_fpt ) != NULL ) {
      char fname[BUFSIZ], lname[BUFSIZ];
      int a, b, c;
      int result;
      result = sscanf( buff, "%s %s %d %d %d", fname, lname, &a, &b, &c );
      if ( result == 5 ) {
        /* convertion OK - validate values or use them as appropriate */
      } else {
        /* flag an error - format of line isn't good */
      }
    }

  3. #3
    Raven
    Join Date
    Nov 2004
    Location
    Inside a Centrifuge
    Posts
    3
    Thanks for the reply, Im new to C >__< so I have some questions about the below code:

    char buff[BUFSIZ]

    BUFSIZ is that some pre-determined size for an array?

    sizeof

    Do I define that, or does it some how automatically calculate size of buff (Do I need some header file for it?)


    Code:
    char fname[BUFSIZ], lname[BUFSIZ];
      int a, b, c;
      int result;
      result = sscanf( buff, "%s %s %d %d %d", fname, lname, &a, &b, &c );
      if ( result == 5 ) {
    Why is lname, fname necessary? (What do they do).

    Result == 5, is that a specific return value, or is any value fine as long as it not 0/-1?

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Look at your file format. Then look at the variable name and we can make a few common sense guesses: "lname" probably stores the "last name", and "fname" probably stores the "first name".

    BUFSIZ is declared in the header stdio.h.

    As to the return value, count the number of format specifiers you're scanning for.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,212
    Quote Originally Posted by xarmenx
    BUFSIZ is that some pre-determined size for an array?
    Macro: int BUFSIZ
    The value of this macro is an integer constant expression that is good to use for the size argument to setvbuf. This value is guaranteed to be at least 256.

    The value of BUFSIZ is chosen on each system so as to make stream I/O efficient. So it is a good idea to use BUFSIZ as the size for the buffer when you call setvbuf.

    Actually, you can get an even better value to use for the buffer size by means of the fstat system call: it is found in the st_blksize field of the file attributes. See section 14.9.1 The meaning of the File Attributes.

    Sometimes people also use BUFSIZ as the allocation size of buffers used for related purposes, such as strings used to receive a line of input with fgets (see section 12.8 Character Input). There is no particular reason to use BUFSIZ for this instead of any other integer, except that it might lead to doing I/O in chunks of an efficient size.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    There is no particular reason to use BUFSIZ for this instead of any other integer, except that it might lead to doing I/O in chunks of an efficient size.
    Sure there is: personal preference and readability.

    Furthermore, unless you're defining your own macro, you don't have to worry about hunting through your code to change all of your hard coded values, when you suddenly find out that 11 isn't big enough...

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > Why is lname, fname necessary? (What do they do).
    Well, if you don't want to store them, you can ignore them (watch the stars)
    Code:
    result = sscanf( buff, "%*s %*s %d %d %d", &a, &b, &c );
    > Result == 5, is that a specific return value, or is any value fine as long as it not 0/-1?
    See, this is where reading the WHOLE manual page on a function is a good idea, so you know what each function does.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  4. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM