我有一个文件,用逗号分隔整数值.例:
10, 5, 213
6, 21, 1
9, 21, 2
Run Code Online (Sandbox Code Playgroud)
我在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;
}
Run Code Online (Sandbox Code Playgroud)
如果您知道文件是格式的10, 5, 213,则可以通过包含逗号来使用fscan():
fscanf(_file, " %d, %d, %d", &i[0], &i[1], &i[2]);
Run Code Online (Sandbox Code Playgroud)
这将从文件中读取您的数字.
并确保检查fscanf调用的返回值.