错误:在“!”令牌之前应为“)”

error: expected ')' before '!' token

提问人:Matthew Marinoff 提问时间:3/23/2015 最后编辑:SpikatrixMatthew Marinoff 更新时间:4/13/2015 访问量:2049

问:

该代码看起来与以前的赋值几乎相同,但无法编译。

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

错误:在“!”令牌之前应为“)”

法典:

#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);
}
c 扫描 feof

评论

3赞 M.M 3/23/2015
试着向橡皮鸭解释每个代币的作用feof! (in)
2赞 Hunter McMillen 3/23/2015
我想你的意思是而不是.!feof(in)feof! (in)
5赞 M.M 3/23/2015
一旦你弄清楚了,就读这个
1赞 chux - Reinstate Monica 3/23/2015
不要使用 .检查返回值以确定代码是否应退出循环。搜索 30 后也退出循环。打印循环应只增加到读取的值数,该值数可能小于 30。while (feof! (in))fscanf()monthnum

答:

0赞 Spikatrix 4/13/2015 #1

你真的想要

while (!feof(in))

而不是

while (feof! (in))

这也是错误的。请参阅为什么 while ( !feof (file) ) 总是错的? 以了解为什么它是错误的。

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

7.21.6.2 fscanf 函数

[...]

  1. 如果在第一次转换(如果有)完成之前发生输入失败,则该函数将返回宏的值。否则,该函数将返回分配的输入项数,如果早期匹配失败,该数目可能少于提供的数量,甚至为零。fscanfEOF

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

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

并从此循环的主体中删除 。要防止阵列溢出,请使用fscanf

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

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

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

而不是

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