简体   繁体   中英

Reading "unfixed" number of integers after a semicolon from a file in c

What is the best way to use sscanf or any other command to read from a file after a semicolon, for example if my file has 5: 4 5 6 7. how can I store the values after the colon in an array. Also the number of integers may vary after the semicolon ie in the example I have given above they are 4 but they can be 5 3 or 10. What is the best way to handle this.

All the numbers being on one line makes it easy. Basically, you want to read a line using fgets() , and split it up into individual numbers by splitting at whitespace, and convert each of those words to an integer. There's a bunch of ways to do that, but I like taking advantage of how strtol() will record where the end of the number it converts is to combine the two steps in one. Something like:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
  char line[] = "5: 4 5 6 7";
  char *curr = line;

  while (*curr) {
    char *end;
    int n = strtol(curr, &end, 10);
    if (curr == end) {
       fputs("Found something not a number!\n", stderr);
       return EXIT_FAILURE;
    } else if (*end == ':') {
      printf("Line header: %d\n", n);
      end++;
    } else {
      printf("Number %d\n", n);
    }
    curr = end;
  }
  return 0;
}

Compiling and running this produces:

Line header: 5
Number 4
Number 5
Number 6
Number 7

You'd of course store the numbers in an array instead of just printing them out, but that should give you the general idea.

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