I need to read an input file like :
1
19 20 41 23
2
41 52 43
3
90 91 941
4
512
5
6
51 61
Each odd line is an integer. Each even line is unknown number of integers.
It is very easy in C++
while( cin >> k ){
............
}
I'm not so used to C, so I couldnt make it in C. Any ways to do it?
Running your input file through:
Results in:
This is the C analog of the code you reference in your original question.
The way I would do it is to break it down into two operations: read a line, then read the integers in that line. Here is a lazy implementation using the standard C library:
I would do one of:
fgetc() to read individual characters and parse them yourself (accumulate digits until you hit whitespace and you have an integer to convert with atoi(); if the whitespace is a newline, then it terminates a list of integers)
fgets() to read a line at a time, and then parse the string (again, look for whitespace separating the values) that it returns.
I came up with a solution like this:
I would break the program in different tasks.
The first step is to be able to read a pair of lines, the first line which tells you the number of numbers to read, and then the second line to read the actual numbers. For this, a function called something like
read_set
might be useful. It should be able to return the numbers read, and signal end of file as well as errors. For this, we can define a data structure such as:and then we can declare our function with the prototype:
The function will allocate memory for
num->data
, and setnum->len
to the correct value. It returns 0 for success, and a set of error conditions otherwise. We might get fancy and use anenum
for return statuses later. For now, let's say that 0 = success, 1 = end of file, and everything else is an error.The caller then calls
read_set()
in a loop:For implementing
read_set()
: it has to read two lines. There are many implementations of reading a full line in C, so you can use any of them, and read a line first, thensscanf()
/strtoul()
it for one number (check its return value!). Once you have the number of numbers,n
, you can read the next line in memory, and do:You can then repeatedly call
sscanf()
orstrtol()
to store numbers innum->data
. You should put in checks to make sure exactlyn
numbers are on that line.Note that you can write
read_set()
in other ways too: read a line character by character, and parse the numbers as you read them. This has the advantage of going over the data only once, and not needing a big buffer to store the whole input line in memory, but the disadvantage is doing low-level stuff yourself and reading data character-by-character may be slow.have a look at getc(3) or scanf(3)