简体   繁体   中英

An efficient way of reading integers from file

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

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]);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM