Getchar()不起作用?

时间:2011-09-09 08:58:47

标签: c

我对 getchar()函数感到困惑,所以我搜索了这个很棒的网站,阅读了所有相关主题,并阅读了K& R书中的getchar()。但是当我运行代码时,在控制台屏幕上键入一个单词,然后点击回车,没有任何反应。我期望显示的字符数。

#include<stdio.h>
int main(void)//doesn't work??
{
int c ;
int count ;

while ( ( c = getchar() ) != EOF )
   count ++ ;

printf( "%d characters\n" , count ) ;
return 0;
}

4 个答案:

答案 0 :(得分:7)

我认为是因为你正在按Enter键并期望循环停止。

条件

while ( ( c = getchar() ) != EOF)
Ctrl + Z时,

仅在Windows上为false。

在UNIX上它是Ctrl + D我认为,如果你使用的是Ubuntu它应该是Ctrl + D

如果您希望循环停止按下输入,请尝试检查'\n'字符。

答案 1 :(得分:2)

如果您使用的是Windows,则ENTER与EOF无关。 这个问题可能会为您解释:

Why doesn't getchar() recognise return as EOF on the console?

答案 2 :(得分:2)

用'\ n'替换EOF,或者在类Unix系统上使用Ctrl + D发送EOF(或者在其他人提到的Windows上按Ctrl + Z)。

编辑:count是错误的,因为你没有将变量初始化为0.未初始化的变量的值将是未定义的,编译器应该警告你。

答案 3 :(得分:0)

EOF表示文件结束,但您没有打开任何文件,所以您希望它如何工作?

int main (void) \\ no problem using these . it just says no arguments to main

例如

int main(  )
 {
   int a=40; 
   main(a); \\ you wont find any error with these
 }

int main( void )
 {
     int a=40;
     main(a);  \\ you get error saying main function cant take arguments
  }

main( ) it can take infinite arguments and whereas main(void) none arguments

这就是为什么当你使用

getch(a) or clrscr(1) your passing arguments to these functions so you get error
                       because they are defined as clrscr( void ) getch (void )

strlen(char *)  \\ can take only one argument 

您可以在标题文件中查看它们

  Try these
  c = 0; count = 0 ; initialize it so that you wont have any garbage value
  while ((c=getchar)!='\n') or may be its AScll value 
  while ((c=getchar)!=13)

  FILE *p;
  p=fopen("hello.txt","r");
  while ( c = getc(p) != EOF ) \  When  it returns end of file while loop exits

 Say You have these content in hello.txt 
 "hello world My name text file"
 for every loop c has the character like h,e,l and when it returns to end it exits

所以EOF主要用于文件我希望你明白这一点