C中的fscanf - 如何确定逗号?

问题描述 投票:0回答:4

我正在通过fscanf()从文件中读取一组数字,我希望将每个数字放入数组中。问题是thosose数字用“,”分隔如何确定fscanf应该读取几个密码,当它在文件中找到“,”时,它会将它保存为整数?谢谢

c io
4个回答
4
投票

这可能是一个开始:

#include <stdio.h>

int main() {
    int i = 0;

    FILE *fin = fopen("test.txt", "r");

    while (fscanf(fin, "%i,", &i) > 0)
        printf("%i\n", i);

    fclose(fin);

    return 0;
}

使用此输入文件:

1,2,3,4,5,6,
7,8,9,10,11,12,13,

...输出是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13

你究竟想做什么?


2
投票

我可能会使用类似的东西:

while (fscanf(file, "%d%*[, \t\n]", &numbers[i++]))
    ;

%d转换一个数字,“%* [,\ t \ n]]”读取(但不指定)任何连续的分隔符运行 - 我将其定义为逗号,空格,制表符,换行符,尽管这是改变你认为合适的东西是相当微不足道的。


0
投票

fscanf(file, "%d,%d,%d,%d", &n1, &n2, &n3, &n4);但如果数字之间有空格则不起作用。 This answer展示了如何做到这一点(因为没有库函数)


0
投票

Jerry Coffin的答案很好,但有几点需要注意:

  1. fscanf在文件末尾返回一个(负)值,因此循环不会正确终止。
  2. 即使没有读取任何内容,i也会递增,因此最终会指向一个超过数据结尾的内容。
  3. 此外,如果在格式参数之间留出空格,fscanf会跳过所有空格(包括\t\n)。

我会选择这样的东西。

int numbers[5000];
int i=0;
while (fscanf(file, "%d %*[,] ", &numbers[i])>0 && i<sizeof(numbers))
{
    i++;
}
printf("%d numbers were read.\n", i);

或者,如果要强制执行数字之间的逗号,可以使用"%d , "替换格式字符串。

© www.soinside.com 2019 - 2024. All rights reserved.