无法理解 - 从 C 文件中读取字符
Unable to understand - reading characters from files in C
我刚开始学习 C 文件处理,想知道我是否可以通过从文件读取输入来执行数学计算,这里是读取字符并在控制台上显示的代码:
int main(void)
{
FILE *p;
char a, b, c, ch;
p = fopen("numbers.txt", "a+");
while((ch = getc(p)) != EOF)
{
fscanf(p, "%c %c %c\n", &a, &b, &c);
printf("%c %c %c\n", a, b, c);
}
fclose(p);
return 0;
}
numbers.txt 包含(每个字符前有一个 space):
2 + 3
5 + 6
6 + 7
获得的输出是:
2 + 3
+ 6
+ 7
我无法理解为什么第一行输出符合预期但第二行和第三行缺少字符,即使在 numbers.txt.
中的每个表达式后都给出了换行符
在 while
循环的每次迭代开始时都会扫描一个额外的字符
while((ch = getc(p)) != EOF)
尝试将 fscanf()
语句作为 while
循环的条件并检查其 return 值。根据cplusplus.com:
On success, the function returns the number of items of the argument
list successfully filled. This count can match the expected number of
items or be less (even zero) due to a matching failure, a reading
error, or the reach of the end-of-file.
If a reading error happens or the end-of-file is reached while
reading, the proper indicator is set (feof or ferror). And, if either
happens before any data could be successfully read, EOF is returned.
因此请尝试将您的 while 条件更改为以下任一条件:
while (fscanf(p, " %c %c %c", &a, &b, &c) != EOF)
或
while (fscanf(p, " %c %c %c", &a, &b, &c) == 3)
在 scanf
格式说明符中使用 whitespace,就像使用 \n
一样,匹配 任意数量 的 whitespace. \n
和下一行的前导 space 被消耗,导致 getc
删除第一个数字而不是前导 space。
我会完全跳过 getc
,正如@BLUEPIXY 建议的那样:
while (fscanf(p, " %c %c %c", &a, &b, &c) == 3) {
printf("%c %c %c\n", a, b, c);
}
我刚开始学习 C 文件处理,想知道我是否可以通过从文件读取输入来执行数学计算,这里是读取字符并在控制台上显示的代码:
int main(void)
{
FILE *p;
char a, b, c, ch;
p = fopen("numbers.txt", "a+");
while((ch = getc(p)) != EOF)
{
fscanf(p, "%c %c %c\n", &a, &b, &c);
printf("%c %c %c\n", a, b, c);
}
fclose(p);
return 0;
}
numbers.txt 包含(每个字符前有一个 space):
2 + 3
5 + 6
6 + 7
获得的输出是:
2 + 3
+ 6
+ 7
我无法理解为什么第一行输出符合预期但第二行和第三行缺少字符,即使在 numbers.txt.
中的每个表达式后都给出了换行符在 while
循环的每次迭代开始时都会扫描一个额外的字符
while((ch = getc(p)) != EOF)
尝试将 fscanf()
语句作为 while
循环的条件并检查其 return 值。根据cplusplus.com:
On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.
If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.
因此请尝试将您的 while 条件更改为以下任一条件:
while (fscanf(p, " %c %c %c", &a, &b, &c) != EOF)
或
while (fscanf(p, " %c %c %c", &a, &b, &c) == 3)
在 scanf
格式说明符中使用 whitespace,就像使用 \n
一样,匹配 任意数量 的 whitespace. \n
和下一行的前导 space 被消耗,导致 getc
删除第一个数字而不是前导 space。
我会完全跳过 getc
,正如@BLUEPIXY 建议的那样:
while (fscanf(p, " %c %c %c", &a, &b, &c) == 3) {
printf("%c %c %c\n", a, b, c);
}