mrudult
mrudult

Reputation: 2570

Read data from file line by line with different data types

I have a .txt file as:

A B C
England vs autralia
2004
100
D E F
japan vs argentina
3045
140
D E F
india vs pakistan
2012
150
J F G
south africa vs india
1967
100
K GHD D
australia vs pakistan
1993
453
Z E Q
pakistan vs england
2013
150  

I want to read it and store in variables. (each line goes to a single variable).

I have this code but it read's one line at a time and as a string.

if ( file != NULL )
{
    i=1;
    char line [ 100 ]; /* line size */
    while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
        {
            fputs ( line, stdout ); /* write the line */
            i++;
        }
    fclose ( file );
}  

Actually I want to read 4 lines at a time. but seems impossible. So I can put the 4 line in a single line separated by a space but in that case scanning multi-word strings will not be possible.

So,How do I do this?

Upvotes: 1

Views: 1293

Answers (2)

wildplasser
wildplasser

Reputation: 44250

Use a counter to determine on which of the four lines you are:

#include <stdio.h>
#include <string.h>

void doit( FILE *file)
{
char line [ 100 ]; /* line size */
unsigned iii;
size_t len;

    for(iii=0;  fgets ( line, sizeof line, file); iii++ ) /* read a line */
        {
        len = strlen(line);
        while (len && line[len-1] == '\n') line[--len] = 0;
        switch (iii % 4) {
        case 0: /* handle first line here */
               break;
        case 1: /* handle second line here */
               break;
        case 2: /* handle third line here */
               break;
        case 3: /* handle fourth line here */
               break;
                }
        }
}

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409186

Read it line by line, and as the format seems to be fixed you always know what types there are on each line.

So e.g. like this pseudo-code:

while (continue_reading)
{
    // E.g. "A B C"
    get_line()
    parse_line_into_three_string()

    // E.g. "England vs autralia"
    get_line()
    parse_whole_line_as_a_single_string()

    // E.g. "2004"
    get_line()
    parse_line_as_a_number()

    // E.g. "100"
    get_line()
    parse_line_as_a_number()

    do_something_with_all_data()
}

Upvotes: 0

Related Questions