Reputation: 269
I'd like to read all integers from a file into the one list/array. All numbers are separated by space (one or more) or end line character (one or more). What is the most efficient and/or elegant way of doing this? Functions from c++ library are prohibited.
I did it this way:
/* We assume that 'buffer' is big enaugh */
int i = 0;
while(fscanf(fp, "%d", &buffer[i]) != EOF) {
++i;
}
Sample data:
1 2 3
4 56
789
9 91 56
10
11
Upvotes: 0
Views: 94
Reputation: 154255
OP's code is close. Test against 1
rather than EOF
so code does not get caught in a endless loop should non-numeric data occur. I'd use a for()
loop, but while
is OK too.
Note that "%d"
directs fscanf()
to first scan and discard any white-space including ' '
and '\n'
before looking for sign and digits.
#define N 100
int buffer[N];
int i,j;
for (i=0; i<N; i++) {
if (fscanf(fp, "%d", &buffer[i]) != 1) {
break;
}
}
for (j=0; j<i; j++) {
printf("buffer[%d] --> %d\n", j, buffer[j]);
}
Upvotes: 1
Reputation: 5141
You can use fgets
to read each line from the file into a string, say char *line
.
Then you can loop through that string char by char and use isDigit
to determine if the character is a digit or not.
To read numbers with more than one digit place each digit in a string and use atoi
to convert them to an integer
Upvotes: 0