gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:48 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com