c - 读取像 1,2,3,4 这样的行时如何在 c 中正确 fscanf?

标签 c file-io input output

void readFile(void) {

    FILE *file;    
    int i;
    char line[100];
    int testnr, testnr2, testnr3, testnr4;
    //testnr = 1;
    //testnr2 = 2;
    //testnr3 = 3;
    //testnr4 = 4;

    file = fopen("test.txt","r");

    fgets(line,500,file); // does not do anything with the first line

    // read in 1,2,3,4
    fscanf(file, "%i %i %i %i", &testnr, &testnr2, &testnr3, &testnr4);      
    printf("%i %i %i %i \n", testnr, testnr2, testnr3, testnr4);    

    fclose(file);
}               

终端中的输出变为:1 32714 -275292160 32767

我该如何修复它,使其成为:1 2 3 4

最佳答案

您还需要读入整数之间的字符。

fscanf( file, "%i,%i,%i,%i", &nr, &nr2, &nr3, &nr4 );

另请注意,fscanf 返回成功读取的次数。所以你可以这样做:

int num_reads = fscanf( file, "%i,%i,%i,%i", ... );
if( num_reads != 4 ) 
{
    // DO ERROR
}
else
{
    // DO SUCCESS
}

关于c - 读取像 1,2,3,4 这样的行时如何在 c 中正确 fscanf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19965663/

相关文章:

c - 为什么这两种计算字数的方法有很大不同?

c - 为什么这个定义宏要执行强制转换?

c - 分配的值不正确 - C

java - 如何在 java 中创建 .dat 文件

c# - 如何删除文件锁? C#

C++:从文件中读取并显示单个项目

c - 二叉树的最低公共(public)祖先(不是二叉搜索树)

java - 自动选择文件 I/O 的缓冲区大小

javascript - 如何分别计算每个部分的总值: Jquery

python - 如何在Python中读取用户输入