c - 错误: expected ')' before '!' token

标签 c scanf feof

该代码看起来与之前的作业几乎相同,但无法编译。

问题似乎出现在 while(feof!(in))

之前

error: expected ')' before '!' token

代码:

#include <stdio.h>

int main (void)
{
    int water_arr[30],monthnum=0;

    FILE* in;
    in = fopen ("water.txt","r");

    while (feof! (in))
        {
            fscanf(in, "%d", &water_arr[monthnum]);
            monthnum = monthnum + 1;
        }

    for (monthnum = 0; monthnum < 30; monthnum++)
        {
            printf("%d",water_arr[monthnum]);
        }

    return (0);
}

最佳答案

你其实想要

while (!feof(in))

而不是

while (feof! (in))

这也是错误的。请参阅Why is while ( !feof (file) ) always wrong?才知道为什么是错的。

正确的方法是使用 fscanf 的返回值作为条件。根据C11标准,

7.21.6.2 The fscanf function

[...]

  1. The fscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

因此,在您的情况下,如果成功,fscanf 将返回 1。因此,使用

while(fscanf(in, "%d", &water_arr[monthnum])==1)

并从此循环体中删除fscanf。为了防止数组溢出,请使用

while(monthnum<30 && fscanf(in, "%d", &water_arr[monthnum])==1)

还有一个问题。由于water_arr是一个本地、非staticint数组,因此它不会自动初始化。从文件中读取数据后,打印整个数组。如果读取的整数数量小于 30,这将导致未定义行为。您应该使用不同的变量并打印数组索引,直到该变量等于 monthnum。喜欢:

int i;
for(i=0 ; i<monthnum ; i++)
    printf("%d",water_arr[i]);

而不是

for (monthnum = 0; monthnum < 30; monthnum++)
{
    printf("%d",water_arr[monthnum]);
}

关于c - 错误: expected ')' before '!' token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200727/

相关文章:

对 C 指针释放感到困惑

c++ - 现代 C/C++ 编译器能否更好地优化 header 中的代码?

c - 函数已被弃用

c - 使用 sscanf 解析不会保留数组以供后续使用

c - 当我按 ctrl + D 时,为什么我的程序会在结束之前打印一些内容?

c - 为什么“while(!feof(file))”总是错误的?

c - 为什么“while(!feof(file))”总是错误的?

c - 链表地址

c - 如何在节点结构中实现字符指针?

C: sscanf 赋值抑制和返回值