Thread: reading string and integers from a text file

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    4

    reading string and integers from a text file

    I am trying to read a text filewith an 'unknown' number of name strings and integer test scores. this is the latest attempt. I only get the first character instead of the string.

    int ReadFile ( char *CharArrayPtr, int *IntArrayPtr )
    {
    int RecordCount = 0;

    rewind ( fin );
    while ( fgets ( &CharArrayPtr[RecordCount], 13, fin ))
    {
    fscanf ( fin, "%d", &IntArrayPtr[RecordCount] );
    RecordCount ++;
    }
    close (fin );
    return ( RecordCount );
    }

    CharArrayPtr is a pointer to a 2D array for the name strings. IntArrayPtr is for the test scores. fin is the pointer to my text file.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Normally, you use fgets to read a whole line, then use sscanf (or whatever you want) to extract the information from the line.

    Code:
    #include <stdio.h>
    
    int ReadFile ( FILE *fin, char (*CharArrayPtr)[20], int *IntArrayPtr ) { 
        char buff[BUFSIZ];
        int i = 0; 
        rewind ( fin ); 
    
        // read each line from the file
        while ( fgets ( buff, BUFSIZ, fin ) != NULL ) {
            // if it contains the data we expect
            if ( sscanf( buff, "%s %d", CharArrayPtr[i], &IntArrayPtr[i]) == 2 ) {
                // then increment the count
                i++;
            } else {
                // some error message perhaps
            }
        }
        return i;
    } 
    
    int main ( ) {
        char    names[100][20];
        int     scores[100];
        int     n = ReadFile( stdin, names, scores );
        int     i;
        printf( "%d records\n", n );
        for ( i = 0 ; i < n ; i++ ) {
            printf( "%2d: %s %d\n", i, names[i], scores[i] );
        }
        return 0;
    }

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    4
    I think I can make that work. Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Convert string of characters to integers
    By Digital_20 in forum C++ Programming
    Replies: 2
    Last Post: 04-02-2008, 09:40 PM
  2. Reading from File
    By Bnchs in forum C Programming
    Replies: 8
    Last Post: 12-09-2007, 03:17 PM
  3. Replies: 9
    Last Post: 03-17-2006, 12:44 PM
  4. Reading a file written by VB
    By nemaroller in forum C++ Programming
    Replies: 8
    Last Post: 07-12-2002, 11:17 PM
  5. inputting line of text vs. integers in STACK
    By sballew in forum C Programming
    Replies: 17
    Last Post: 11-27-2001, 11:23 PM