消除整数列表输入中的逗号

时间:2014-11-26 03:42:19

标签: c file-io

我有一个文件,用逗号分隔整数值。 例如:

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

我的文件IO在C中生锈了,我只是在输入的第一个整数值(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;
}

1 个答案:

答案 0 :(得分:5)

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

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

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

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