【问题标题】:error: expected ')' before '!' token错误:在 '!' 之前应为 ')'令牌
【发布时间】:2015-05-25 21:08:36
【问题描述】:

代码看起来与之前的分配几乎相同,但它无法编译。

问题似乎出现在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);
}

【问题讨论】:

  • 尝试向橡皮鸭解释每个令牌在feof! (in)中的作用
  • 我认为您的意思是 !feof(in) 而不是 feof! (in)
  • 一旦你弄清楚了,read this
  • 不要使用while (feof! (in))。检查fscanf() 的返回值以确定代码是否应该退出循环。一旦monthnum 搜索 30 次,也退出循环。打印循环应该只达到读取的值的数量,可能小于 30。

标签: c scanf feof


【解决方案1】:

你真的想要

while (!feof(in))

而不是

while (feof! (in))

这也是错误的。请参阅Why is while ( !feof (file) ) always wrong? 了解错误原因。

相反,正确的方法是使用fscanf 的返回值作为条件。按照 C11 标准,

7.21.6.2 fscanf 函数

[...]

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

因此,在您的情况下,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]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多