user4664035
user4664035

Reputation:

How to read numbers from a text file properly?

I would like to write a lottery program in C, that reads the chosen numbers of former weeks into an array. I have got a text file in which there are 5 columns that are separated with tabulators. My questions would be the following:

I used to write a C program for a "Who Wants to Be a Billionaire" game. In that one I used a kind of function that read each line into an array that was big enough to hold a whole line. After that I separated its data into variables like this:

line: "text1";"text2";"text3";"text4"endline (-> line loaded into a buffer array)
text1 -> answer1 (until reaching the semicolon)
text2 -> answer2 (until reaching the semicolon)
text3 -> answer3 (until reaching the semicolon)
text4 -> answer4 (until reaching the end of the line)
endline -> start over, that is read a new line and separate its contents into variables.

It worked properly, but I don't know if it was good enough for a programmer. (btw I'm not a programmer yet, I study Computer Science at a university)

Every answers and advice is welcome. Thanks in advance for your kind help!

Upvotes: 0

Views: 124

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 755064

The scanf() family of functions don't care about newlines, so if you want to process lines, you need to read the lines first and then process the lines with sscanf(). The scanf() family of functions also treats white space — blanks, tabs, newlines, etc. — interchangeably. Using tabs as separators is fine, but blanks will work too. Clearly, if you're reading and processing a line at a time, newlines won't really factor into the scanning.

int lottery[100][5];
int line;
char buffer[4096];

for (line = 0; fgets(buffer, sizeof(buffer), stdin) != 0 && line < 100; line++)
{
    if (sscanf(buffer, "%d %d %d %d %d", &lottery[line][0], &lottery[line][1],
               &lottery[line][2], &lottery[line][3], &lottery[line][4]) != 5)
    {
        fprintf(stderr, "Faulty line: [%s]\n", line);
        break;
    }
}

This stops on EOF, too many lines, and a faulty line (one which doesn't start with 5 numbers; you can check their values etc in the loop if you want to — but what are the tests you need to run?). If you want to validate the white space separators, you have to work harder.

Maybe you want to test for nothing but spaces and newlines after the 5 numbers; that's a bit trickier (it can be done; look up the %n conversion specification in sscanf()).

Upvotes: 3

Related Questions