简体   繁体   English

getchar()函数和EOF

[英]getchar() function and EOF

I was practicing C program that i read from The C ANSI Programming Language Second Edition I learn about getchar() function.And the book say that getchar() read the character from stdin until newline character or EOF has been reached.And in the book i try to rewrite the program to count character using getchar() function.The code is fine when compiling. 我正在练习从The C ANSI Programming Language Second Edition阅读的C程序,我了解了getchar()函数,并且书上说getchar()从stdin读取字符,直到到达换行符或EOF 。我尝试使用getchar()函数重写程序以计算字符数。编译时代码很好。 The problem is the code unable to display the long of character. 问题是代码无法显示字符长。

Here is the code: 这是代码:

#include <stdio.h>

int main (void){
   long nc;

   nc=0;
   while(getchar()!=EOF)
      nc++;
   printf("%ld\n",nc);

   return 0;
}

But when i change the EOF to newline character \\n the code working as i expected but only display the long of character only one line. 但是,当我将EOF更改为换行符\\n ,代码按我的预期工作,但只显示一行的长字符。 After that the code terminate. 之后,代码终止。

My question is what is EOF exactly is and what is the difference between EOF and newline character. 我的问题是EOF到底是什么, EOF和换行符之间有什么区别。

Is there other way to fix this program? 还有其他解决方案吗?

getchar() returns EOF when you get to the end of the file. 到达文件末尾时, getchar()返回EOF It returns \\n when you get to the end of the line. 当您到达行尾时,它返回\\n This is why your loop finishes when it gets to the end of the line if you replace EOF with \\n . 这就是为什么如果将EOF替换为\\n ,则循环到达行尾时会结束的原因。

EOF means End of File and you get that when your getting to the end of a file with getchar() . EOF表示End of File ,当您使用getchar()到达End of File ,您会得到提示。 You get \\n when you get to the end of a line. 您到达行尾时会得到\\n

When you now want it, so that it prints the text again use this: 现在,当您需要它以便再次打印文本时,请使用以下命令:

#include <stdio.h>

int main(void) {
    int c, nc = 0;

    while ((c = getchar()) != '\n') {
        nc++;
        putchar(c);
    }

    printf("%d\n",nc);

    return 0;

}

EOF is the end of file. EOF是文件的末尾。 It does not mean the end of your "long of character". 这并不意味着您“长相符”的结尾。 If you just type many characters occupying several lines on the command line screen, the program still does not get the EOF unless you type Ctrl+D simulating the end of file. 如果仅在命令行屏幕上键入占用多行的许多字符,则除非您键入Ctrl + D模拟文件结尾,否则程序仍不会获得EOF。 When you change EOF to "\\n", the program requires the end of line. 当您将EOF更改为“ \\ n”时,该程序需要换行。 And when you finish the first line, the program get the end of the first line and run. 当您完成第一行时,程序将到达第一行的末尾并运行。 That is why the code works as you expected but only display the long of character only one line. 这就是为什么代码可以按您预期的那样工作,但只在一行中显示长字符的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM