[英]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.使用 sscanf 或任何其他命令从分号后读取文件的最佳方法是什么,例如,如果我的文件有 5: 4 5 6 7. 如何将冒号后的值存储在数组中。 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.
此外,分号后的整数数量可能会有所不同,即在我上面给出的示例中,它们是 4,但它们可以是 5、3 或 10。处理这个问题的最佳方法是什么。
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.基本上,您想使用
fgets()
读取一行,并通过在空格处拆分将其拆分为单独的数字,并将这些单词中的每一个转换为整数。 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.有很多方法可以做到这一点,但我喜欢利用strtol()如何记录它转换的数字的结尾是将两个步骤合二为一。 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.您当然会将数字存储在数组中,而不仅仅是将它们打印出来,但这应该会给您一个总体思路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.