无法理解getchar和putchar在此处的角色 #包括 #包括 int main() { INTC; c=getchar(); 而(c!=EOF){ 普查尔(c); } 返回0; }
当我编译并给出输入ABC,然后按enter键时,永无止境的循环像AAAAAAAA一样开始 现在看看下面的代码无法理解getchar和putchar在此处的角色 #包括 #包括 int main() { INTC; c=getchar(); 而(c!=EOF){ 普查尔(c); } 返回0; },c,getchar,putchar,C,Getchar,Putchar,当我编译并给出输入ABC,然后按enter键时,永无止境的循环像AAAAAAAA一样开始 现在看看下面的代码 #include <stdio.h> #include <stdlib.h> int main() { int c; c = getchar(); while (c != EOF) { putchar(c); } return 0; } #包括 #包括 int main() { INTC; c=getc
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
}
return 0;
}
#包括
#包括
int main()
{
INTC;
c=getchar();
而(c!=EOF){
普查尔(c);
c=getchar();//添加了这一行
}
返回0;
}
在这个程序中,当我输入ABC时,输出是ABC。
有人能解释一下为什么它不只是显示一个a作为输出吗?看看下面你提到的代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar (); // added this single line
}
return 0;
}
当c=getchar()时代码>执行&如果您在运行时以ABC
的形式提供输入,并按ENTER(\n)
,则c
的时间保持第一个字符A
。
接下来来循环,您的条件是c=EOF
即A=EOF
始终为真&它将无限次打印A
,因为您不要求第二次输入,所以c
保持A
以上代码的正确版本是
int main(void){
int c;
c = getchar();
while (c != EOF) {
putchar(c);
}
return 0;
}
案例2:-现在查看第二个代码
int main(void){
int c;
while ( (c = getchar())!=EOF) { /* to stop press ctrl+d */
putchar(c);
}
return 0;
}
有人能解释一下为什么它不显示单个a作为输出吗?为什么它应该只打印A
,它会打印您给定的任何输入,比如ABC
&等等。请注意,getchar()
与缓冲输入一起工作,即当您按ENTER
getchar()
时,将读取到该值&当然,当没有剩余内容可读取时getchar()
返回EOF
。您按[Enter]键生成一个'\n'
,用getchar()
读入c
,然后在(c!=EOF)
时测试(永远)。添加额外的行尝试一个额外的输入来停止无限循环(您可以在windows上按ctrl+d
,或ctrl+z
,以生成手动EOF
——但请参见)Resd本文:为什么您希望第二个示例只打印一个a
?
int main(void){
int c;
c = getchar();
while (c != EOF) { /*condition is true */
putchar(c);
c = getchar ();/*After printing ABC, it will wait for second input like DEF, unlike case-1 */
}
return 0;
}