gpt4 book ai didi

c - 从整数列表输入中消除逗号

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

我有一个文件,里面填满了用逗号分隔的整数值。示例:

10, 5, 213
6, 21, 1
9, 21, 2

我对 C 中的文件 IO 感到生疏,我只是陷入无限循环读取输入的第一个整数值 (10)。为什么我陷入了循环?它不应该读入 3 个数字(忽略逗号和空格)并转到下一行吗?

int main(void)
{
//Open a file to read
FILE *_file = fopen("input.txt", "r");
//Used for scanning characters
int i[3];
i[0] = 0;
i[1] = 0;
i[2] = 0;
char buffer[1024] = { 0 } ;

//Check to make sure the file was open
if (_file == NULL) {
fprintf(stderr, "ERROR: File Not Found\n");

} //Else, file was opened
else {
//Scan the entire file and print the integer
fscanf(_file, "%d[^,] %d[^,] %d[^,]", &i[0], &i[1], &i[2]);

while (!feof(_file))
{
printf("%d\n", i[1]);

fscanf(_file, "%d[^,] %d[^,] %d[^,]", &i[0], &i[1], &i[2]);
}


}
fclose(_file);

getchar();
return 0;
}

最佳答案

如果您知道文件的格式为 10, 5, 213,则可以通过包含逗号来使用 fscan():

fscanf(_file, " %d, %d, %d", &i[0], &i[1], &i[2]);

这将从文件中读取您的号码。

并确保检查 fscanf 调用的返回值。

关于c - 从整数列表输入中消除逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27140963/

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