【问题标题】:Learning C, looping error [duplicate]学习C,循环错误[重复]
【发布时间】:2016-01-16 23:10:20
【问题描述】:

我的任务是创建一个从小写到大写的简单程序。但是,在测试我的输入是否正确打印时,我注意到每次输入一个字符时,它总是会再次循环,即使它不应该这样做。

#include <stdio.h>

int main() {
  char input;

  //enter a character
  //set the given input char to variable
  printf("Enter a character in lower case: \n");
  input = getchar();

  //Sentinel value is Q
  while (input != 'Q'){
    printf("you entered %c.\n",input);
    printf("\n");

    printf("Enter a character in lower case: \n");
    input = getchar();  //gets input from inside the loop
  }
  printf("Goodbye \n");
  return 0;
}

测试输出(我输入字符'g'并按回车一次):

Enter a character in lower case:
g
you entered g.

Enter a character in lower case:
you entered
.

我没有发现问题。

【问题讨论】:

标签: c


【解决方案1】:

这里的问题是由按 ENTER 键输入到 stdin 中的 newline 字符引起的。在进行下一个输入之前,您需要清除输入缓冲区,例如添加

 while (getchar() != '\n');

在要求下一个输入之前。

也就是说,getchar() 返回一个intchar 可能不足以始终保存返回值,请更改

 char input;

int input = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 2013-02-27
    • 2022-07-22
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多