我不明白为什么printf()循环后的while调用不被执行?
int main(){
while((getchar()) != EOF){
characters ++;
if (getchar() == '\n'){
lines++;
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}发布于 2020-03-16 09:58:10
我想你是想这么做
#include<stdio.h>
int main()
{
int characters=0,lines=0;
char ch;
while((ch=getchar())!= EOF)
{
if (ch == '\n')
lines++;
else
{
characters++;
while((ch=getchar())!='\n'&&ch!=EOF); //is to remove \n after a character
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}输出:
a
s
d
f
^Z
lines: 1
Chars: 4
Process returned 0 (0x0) execution time : 8.654 s
Press any key to continue. 注意:^Z(ctrl+z)是将EOF发送到stdin (在windows中)
发布于 2020-03-16 09:40:15
你必须小心你在while循环中的治疗。事实上,你错过了在while语句中读到的每一个字符。为了以后使用它,您必须保存这个输入。
正确的语法应该是while(( c = getchar()) != EOF)。
发布于 2020-03-16 09:58:34
你可能在寻找这样的东西:
#include <stdio.h>
int main()
{
int characters = 0;
int lines = 0;
int c;
while ((c = getchar()) != EOF) {
characters++;
if (c == '\n') {
lines++;
characters--; // ignore \n
}
}
printf("lines: %8d\n", lines);
printf("Chars: %8d", characters);
return 0;
}while ((c = getchar()) != EOF)看起来可能有点混乱。
基本上,它调用getchar,将返回的值放入c和,然后检查c是否等于EOF。
https://stackoverflow.com/questions/60703295
复制相似问题