我的fscanf()
代码正在从文件中读取数据但不是我期望的。它应该是:
A 1 3
B 2 5
等终端
我的数据文件上面有这些
A 4 7
B 8 6
C 4 6
D 7 3
E 10 2
F 3 8
G 1 10
在终端上阅读时,我得到了这个......
A 4 7
4 7
8 6
8 6
4 6
4 6
7 3
7 3
10 2
10 2
3 8
3 8
1 10
1 10
我希望在终端上读取的数据是它在我的文本文件中的确切格式。以下代码就是我们
fp = fopen("data.txt", "r");
if (fp == NULL)
{
printf("File, data.txt wasn't read succesfully. \n");
fclose (fp);
}
else
{
printf("Reading data from data.txt \n");
//read in data
while (1)
{
dataTest = fscanf(fp, "%c %d %d", &c, &t1, &t2);
fscanf(fp,"%c", &nl);
if (dataTest == -1) break;
printf("%c %d %d \n", c, t1, t2);
}
printf("Data read succesfully ! \n");
fclose (fp);
}
答案 0 :(得分:0)
改变这个:
dataTest = fscanf(fp, "%c %d %d", &c, &t1, &t2);
fscanf(fp,"%c", &nl);
对此:
dataTest = fscanf(fp, "%c %d %d\n", &c, &t1, &t2);
或(取决于您的文件格式):
dataTest = fscanf(fp, "%c %d %d\r\n", &c, &t1, &t2);