【问题标题】:while loop prints the same statement twice when using getchar() and putchar() [duplicate]使用 getchar() 和 putchar() 时,while 循环会打印相同的语句两次 [重复]
【发布时间】:2017-02-12 21:19:22
【问题描述】:

我正在编写一个简单的代码,它从用户那里获取一个字符并打印它,如果该字符是 q,则循环中断。但是我得到的输出打印了两次打印语句,第二次打印什么都没有,请看一下图像。为什么要打印两次?

#include<stdio.h>
void main()
{
  char c;
  printf("Enter a character: ");
  c=getchar();
  while(c!='q')
  {
     putchar(c);
     printf("\nEnter a character: ");
     c=getchar();
  } 
}

【问题讨论】:

  • 寻求代码帮助的问题必须在问题本身中包含代码、所需的输出和输入。没有截图。请发帖minimal reproducible example
  • 请张贴代码而不是图片 - 我看不懂
  • 跳过换行符...
  • do not put images of code and/or text output。复制文本并粘贴到这里
  • 抱歉放图片了。我已经编辑并编写了代码。请看一看。

标签: c


【解决方案1】:

您正在按 Return/Enter 键作为输入的一部分。它保留在输入流中,并在下一次迭代中立即被getchar 拾取。

如果格式化输入是一个选项,您可以使用scanf 在等待字符输入时跳过空白字符:

scanf(" %c", &c); // Note the leading white-space, it's what does the skipping

如果您确实继续使用getchar,请注意其返回类型,即int。当输入流耗尽时返回EOF,并且该值不是有效字符,而是一个整数。

【讨论】:

  • 谢谢!那行得通。我有个问题。 getchar() 函数不应该每次迭代使用一个字符吗?为什么在第二次迭代中将 return 作为输入?
  • @ManikumarPerla - 因为输入流是缓冲的。来自硬件的击键存储在一个特殊的数组中,您的程序每次调用getchar 时都会从该数组中读取。它的设计是为了确保不会丢失任何输入。
  • 更重要的是,返回字符一个字符;当您键入x 并返回时,您正在输入两个字符。 getchar() 函数读取所有字符,而不仅仅是打印字符。
  • 谢谢! @JonathanLeffler
【解决方案2】:

什么是缓冲区?
临时存储区域称为缓冲区。所有标准输入和输出设备都包含输入和输出缓冲区。在标准 C/C++ 中,流是缓冲的,例如在标准输入的情况下,当我们按下键盘上的键时,它不会发送到您的程序,而是由操作系统缓冲,直到时间分配给程序.

键入“while ((getchar()) != ‘\n’);”读取缓冲区字符直到结束并丢弃它们(包括换行符)并使用它清除输入缓冲区并允许在所需容器中输入。

以下代码可以正常工作:

#include<stdlib.h>
void main()
{
    char c;
    printf("Enter a character: ");
    c = getchar();
    while(c != 'q')
    {
        putchar(c);
        // flushes the standard input (clears the input buffer)
        while ((getchar()) != '\n');
        printf("\nEnter a character:");
        c = getchar();
    }

}

【讨论】:

  • 谢谢!那行得通。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
相关资源
最近更新 更多