c - C程序循环重复两次而不是一次
问题描述
我刚开始编码,很抱歉这个愚蠢的问题。这是C编程。当用户输入Y
时,代码按预期运行。如果用户输入N
或任何其他字符,程序会循环,但由于某种原因它会重复同一行两次。例如:
Input: Y
Output: The game will now start!
Input: N
Output: Waiting...
Would you like to start the game? <Y/N>:
is not a valid response
Would you like to start the game? <Y/N>:
如您所见,线路双打,我该如何解决这个问题?
do {
printf("Would you like to start the game? <Y/N>: ");
scanf("%c", &cGameStart);
if (cGameStart == 'Y')
printf("\nThe game will now start!\n");
if (cGameStart == 'N')
printf("\nWaiting...\n\n");
if ((cGameStart != 'Y') && (cGameStart != 'N'))
printf("%c is not a valid response\n", cGameStart);
} while (!(cGameStart == 'Y'));
解决方案
该评论与问题无关。
问题是\n
缓冲区中留下的字符scanf
。吃它,它会按预期工作。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char cGameStart;
do {
printf("Would you like to start the game? <Y/N>: ");
scanf("%c", &cGameStart);
if (cGameStart == 'Y')
printf("\nThe game will now start!\n");
if (cGameStart == 'N')
printf("\nWaiting...\n\n");
if ((cGameStart != 'Y') && (cGameStart != 'N'))
printf("%c is not a valid response\n", cGameStart);
fgetc(stdin);
} while (!(cGameStart == 'Y'));
printf("Game started\n");
}
推荐阅读
- python - Autoencoder,steps_per_epoch,应该包含什么值?
- php - 如何正确使用 PHP 会话变量来执行用户登录?
- google-sheets - 简化谷歌表格中的数据
- java - 生成签名的 apk - 获取密钥失败:给定最终块未正确填充
- java - 如何从多个数据库引用中获取相同的 recyclerview
- c - 无法使用 papi.h 运行 PAPI 代码,错误:无法在 GCC 中打开共享对象文件
- python - 使用自定义 __getattribute__ 时出现 IPython REPL 错误
- c# - 如何在 C# 中使用“MemoryMappedFile.CreateNew”写入和读取“double”类型的变量?
- jupyter-notebook - Google Colob:Jupyter Notebooks 中没有工具栏
- php - 将 PHP 连接到 Google 表格文件