c - 为什么 getchar 和 putchar 会出现这种情况

标签 c

如果我输入 abc 作为文本流,getchar() 会读取它并 putchar 打印它。我使用 printf 语句来跟踪到底发生了什么。但是在打印输入文本流的字符后,我得到了一个奇怪的输出。它再次进入 while 循环并执行这两个 printf 语句,即当 i4 时。这是否将我的 Enter 键作为输入。如果"is",我也尝试使用 fflush ,但这又产生了另一个问题。在我 fflush 使用 getchar 创建问题后,没有打印任何字符。为什么会发生这种情况以及如何解决它?

如果我使用 fflush(stdin) 会发生什么

#include <stdio.h>
main(){
   c=getchar();
   fflush(stdin);
   while(c!= EOF)
   {
     putchar(c);
     c=getchar();
    fflush(stdin);
   }
}

使用fflush时,我在控制台上写ABC。它只是 getchar() 'a' 并打印它。它甚至没有得到剩余的字符。

下面是我在使用fflush之前所说的主程序。

#include <stdio.h>

main()
{
    int c,i=1;

    c=getchar();

    while(c!= EOF)  // while(c=getchar!=EOF) putchar(c);
    {
      printf("\n\nthis is upper %d time in loop i.e. before the putchar\n\n",i);
      putchar(c);
      printf("\n\nthis is down %d time in loop i.e. after the putchar\n\n",i);
      c=getchar();
      i++;
    }
}

最佳答案

#include <stdio.h>

int main(){
    int c;

    while((c=getchar())!=EOF && c != '\n'){
        putchar(c);
    }
    return 0;
}
<小时/>
while((c=getchar())!=EOF){
    if(c == '\n')
        break;//exit this while-loop
    putchar(c);
}

关于c - 为什么 getchar 和 putchar 会出现这种情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25735211/

相关文章:

c - 如何将每个字符一一打印出来?

c++ - 调用drawow会导致堆损坏

c++ - 将 TreeView 控件滚动到顶部

计算并输出两个指针的差值

c - C 中的静态库包含问题

检查二维数组中的坐标以用于 C 中的雷区游戏

c++ - C/C++ 控制CPU使用率

c - 登录脚本未按预期比较字符串输入

c++ - 将 std::string 传递给 C 风格的 API 是否安全?

c - strtol 重用参数