I've tried with a for loop thats using fscanf until there is a new line, but that won't work.
Variations on fscanf(in, "%d,%d\n", &x, &y)
, as in OP's prior question, fail to detect end-of-line. The '\n'
in the format will match any white-space on input including '\n'
, ' '
, '\t'
,etc.
Simplistic usage of fscanf(..., "%d",...)
can readily fail as "%d"
will consume all leading white-space with no discrimination between '\n'
and other white-spaces.
How can i fill my array ...
Although possible to use fscanf()
to solve this task, consider fgets(), strtol().
The best approach is to use fgets()
to reach a line: all characters up to and including the one final '\n'
. Then use strtol()
, strtoll()
, etc. to read the integers.
long
integers and spacing each needs reasonable less than 21 characters. To accommodate extra leading zeros spacing, etc, let use 2x the anticipated size needs.
#define CHAR_PER_NUMBER 21
#define NUM_PER_LINE 20
#define LINE_NUM 20
#define LINE_SIZE (NUM_PER_LINE * CHAR_PER_NUMBER * 2)
long array[LINE_NUM][NUM_PER_LINE];
// read data
for (int i = 0; i < LINE_NUM; i++) {
char buf[LINE_SIZE + 1]; // +1: room for the appended the null character
if (fgets(buf, sizeof buf, in) == NULL) {
buf[0] = '\0';
}
// Now parse the line
char *p = buf;
for (int j = 0; j < NUM_PER_LINE; j++) {
char *endptr;
array[i][j] = strtol(p, &endptr, 10);
if (p == endptr) {
array[i][j] = -1; // no conversion
}
p = endptr; // advance to the next number
}
}
Additional concerns including handling pathological long lines, values outside the long
range, I/O error handling and efficiency details.
Should input consists of text representing floating-point, a more generous max size per value is warranted.