我的C程序没有提供预期的输出

我的C程序没有提供预期的输出,c,C,我是一名编程初学者,正在学习C语言。我试图从文件中读取内容并对其进行一些处理 以下是我编写的程序: #include <stdio.h> int main() { FILE *fp ; int k = 0 ; char c ; while (c = getc(stdin)) { if (c == 'a') { ++k; } } printf ("th

我是一名编程初学者,正在学习C语言。我试图从文件中读取内容并对其进行一些处理

以下是我编写的程序:

#include <stdio.h>

int main()
{
    FILE *fp ;
    int k = 0 ;

    char c ;
    while (c = getc(stdin))
    {
        if (c == 'a')
        { 
            ++k;
        }
    }

    printf ("the value of k is %i" , &k) ;
}
但是我在控制台中没有得到任何输出。 我在另一个在线IDE上运行了它,我得到一个运行时错误,说“超过了时间限制”

没有产出的原因可能是什么。 是不是因为我需要以某种方式指定EOF字符,而在没有EOF字符的情况下,程序继续运行

从答案中获得帮助后,我将代码替换为以下代码:

#include <stdio.h>

int main()
{
    FILE *fp ;
    int k = 0 ;

    char c ;
    while (c  = getc(stdin) != EOF)
    {
        if (c == 'a')
        { 
            ++k;
        }
   }


   printf ("the value of k is %i" , k) ;
}
它是否从一开始就以某种方式达到EOF?为了验证这一点,我尝试将字符与“h”进行比较,并得到相同的输出

是因为getc返回整数,而整数与文本中的任何字符都不匹配吗


非常感谢所有的见解。代码在最后运行。干杯

您的编译器应该警告您:

while (c = getc(stdin) != EOF)
警告:将赋值结果用作不带括号的条件[
-Wparentheses
]

因为
=(不等式)有一个over
=
(赋值),该行被解释为

while (c = (getc(stdin) != EOF))
           ^                  ^
请注意意外的括号,因此
c
的值只能是零或一,因此
c=='a'
永远不会为真,因为
'a'
永远不会等于1

改成

while ((c = getc(stdin)) != EOF)
       ^               ^
可以给你想要的结果


你应该考虑删除<代码>文件*FP因为它根本不做任何事情。它定义了一个指针,但以后永远不会使用,并且可能会被编译器优化掉。

FILE*fp
不会打开任何文件。当
c=getc(stdin)
变为false时,它只声明一个指向文件对象的指针?需要更改此条件以考虑EOF您显示的代码存在多个问题。首先返回一个
int
。这是非常重要的。它也不会在输入结束时返回零。然后
&k
会给您一个指向
k
的指针。我建议您重新开始。
getc
将读取的
char
作为
unsigned char
转换为
int
,或在文件或错误结束时返回
EOF
,而不是
0
。除非出现中断条件,否则循环将永远不会中断。
char c
->
int c
while…
->
while((ch=getc(stdin))!=EOF)
while (c = (getc(stdin) != EOF))
           ^                  ^
while ((c = getc(stdin)) != EOF)
       ^               ^