c程序设计语言上的习题答案有些不懂,希望大家帮忙讲解下。
#include <stdio.h>
int main(void)
{
int blanks, tabs, newlines;
int c;
int done = 0;
int lastchar = 0;
blanks = 0;
tabs = 0;
newlines = 0;
while(done == 0)
{
c = getchar();
if(c == ' ')
++blanks;
if(c == '\t')
++tabs;
if(c == '\n')
++newlines;
if(c == EOF)
{
if(lastchar != '\n')
{
++newlines; /* this is a bit of a semantic stretch, but it copes
* with implementations where a text file might not
* end with a newline. Thanks to Jim Stad for pointing
* this out.
*/
}
done = 1;
}
lastchar = c;
}
printf("Blanks: %d\nTabs: %d\nLines: %d\n", blanks, tabs, newlines);
return 0;
}
if(c == EOF)
{
if(lastchar != '\n') …
这一部分都不是很明白 好像直接用while((c=getchar())!=EOF)判读的话,按回车键,就直接输出了。但是这里不会。但是不知道为什么。希望大家指点下。谢谢了。
c语言,求助, EOF c程序设计语言
[解决办法]
if(c == '\n')
++newlines;
回车在这里判断啦!
[解决办法]
你的写法更简洁。
[解决办法]
你的写法更简洁 ,这样写就是为了下面的记录newlines变量的判断,当写完一行换行再输入文件结束标志时正确统计出写入的行数。
if(c == EOF)
{
if(lastchar != '\n')
{
++newlines; /* this is a bit of a semantic stretch, but it copes
* with implementations where a text file might not
* end with a newline. Thanks to Jim Stad for pointing
* this out.
*/
}
done = 1;
}
[解决办法]
这里的EOF 是end of file 意思在windows下按CTRL+Z键表示EOF,Linux下按CTRL+D键表示EOF,然后就会有输出了
[解决办法]
仔细看一下注释,原书是你的写法,但后来Jim Stad 发现了在有的操作系统中,其尾行并非以 newline 结尾。为此专门置信给k&R, 将程序改为如此,天下并非只有 windows