C中的getchar()while循环之后不打印
getchar() in C with while looping not printing afterwards
我不明白为什么 while
循环后的 printf()
调用没有被执行?
int main(){
while((getchar()) != EOF){
characters ++;
if (getchar() == '\n'){
lines++;
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}
你必须小心你在 while
循环中的治疗。实际上,您错过了 while 语句中读取的每个字符。您必须保存此输入,以便以后使用。
正确的语法是 while(( c = getchar()) != EOF)
我认为你正在尝试这样做
#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(in windows)
您可能正在寻找这样的东西:
#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
。
我不明白为什么 while
循环后的 printf()
调用没有被执行?
int main(){
while((getchar()) != EOF){
characters ++;
if (getchar() == '\n'){
lines++;
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}
你必须小心你在 while
循环中的治疗。实际上,您错过了 while 语句中读取的每个字符。您必须保存此输入,以便以后使用。
正确的语法是 while(( c = getchar()) != EOF)
我认为你正在尝试这样做
#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(in windows)
您可能正在寻找这样的东西:
#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
。