0

我有两个文件,2dim.dat 和 3dim.dat,它们的第 3 行分别包含以下内容:

2 12

1 0 0

他们的第 3 行是唯一与我们的兴趣相关的行。编写了一个函数,为我们计算该行中有多少个数字,然后程序构造一个具有那么多维度的无符号整数数组。我知道我可以通过执行将 2dim.dat 中的值 2 和 12 分配到 C 程序中该数组的维度中

if(fscanf("%hu %hu", &number[0], &number[1]) == 2){}

对 3dim.dat 也是如此。

如果我收到的文件在一行中包含更多值,例如 4、20 甚至 270,该怎么办?我不知道如何告诉 fscanf 在其第一个参数中使用空格分隔 270 次 %hu 重复,然后添加我们数组的所有维度。

4

1 回答 1

0

示例代码

#include <stdio.h>

int main(void){
    //input line_buff like fgets(line_buff, sizeof(line_buff), fp);
    char line_buff1[64] = "4 20 270";
    char line_buff2[64] = "4 20";
    unsigned short number[3];
    int i, count;
    //Succeed in reading three, be count = 3
    count = sscanf(line_buff1, "%hu %hu %hu", &number[0], &number[1], &number[2]);
    for(i=0;i<count;++i)
        printf("%hu\n", number[i]);

    //Succeed in reading two, be count = 2, fail number[2]
    count = sscanf(line_buff2, "%hu %hu %hu", &number[0], &number[1], &number[2]);
    for(i=0;i<count;++i)
        printf("%hu\n", number[i]);
    return 0;
}
于 2013-05-26T22:46:40.763 回答