【发布时间】:2015-07-20 16:35:02
【问题描述】:
我目前正在尝试自学 C,因为我相信这将是 C++ 和 C# 的一个很好的选择(以及在课程开始之前获得先机)。所以我决定在这里写这个循环:
#include <stdio.h>
int main()
{
bool continueLoop = true;
char response;
printf("ARE YOU READY TO RUMBLE?!?!\n Y/N\n");
response = getchar();
int counter = 0;
do
{
counter++;
if (response == 'Y')
{
printf("AWESOME!");
continueLoop == false;
return 0;
}
else if (response == 'N')
{
printf("YOU FAIL!");
continueLoop == false;
return 0;
}
if (continueLoop == true)
{
printf("I do not understand your input!\n");
printf("Please reinput! Y/N\n");
response = getchar();
}
if(counter == 5)
{
printf("Exiting!");
continueLoop == false;
goto exit;
}
}while (continueLoop == true);
exit:
return 0;
}
我的问题如下:为什么如果我输入例如“M”作为我的答案,它会自动循环两次;但是,如果给定适当的条件,则正确终止。
另外,我是否应该将响应转换为单个长度的数组,然后尝试以某种方式比较它,而不是 getchar(),或者应该通过 printf 语句来完成 printf("ARE YOU READY TO RUMBLE?!? \n %s", response);
如果有帮助,我将使用 C-Lion 作为我的 IDE,因为我拒绝在 vi、emacs 或记事本中编写任何代码。
编辑代码
int main()
{
char response;
printf("ARE YOU READY TO RUMBLE?!?!\n Y/N\n");
scanf(" %c", &response);
int counter = 0;
while (counter < 5)
{
counter++;
if (response == 'Y')
{
printf("AWESOME!");
return 0;
}
else if (response == 'N')
{
printf("YOU FAIL!");
return 0;
}
else
{
printf("I do not understand your input!\n");
printf("Please reinput! Y/N\n");
response = getchar();
}
}
return 0;
}
【问题讨论】:
-
输入
M时按两个键。这就是循环执行两次的原因。当你想要比较两个东西时使用==,当你想要分配两个东西时使用=。还使用goto我们被认为是不好的做法。在这种情况下,您可以将goto替换为break。 -
旁注:
while (continueLoop)就够了。 -
.... 根据 Cool Guy 的评论,第二个键是 Enter 键。
-
getchar()等待换行,并返回您第一次输入的字母,然后返回换行。也永远不要做while (continueLoop == true)。只需使用while (continueLoop),因为 C 认为所有非零值都为真。 -
@LeeDanielCrocker
getchar(3)不会等待任何事情。是终端设备驱动程序逐行提供输入,因此 stdio 阻塞等待输入,直到输入换行符并且终端驱动程序刷新输入队列。这可以通过禁用ICANON(规范模式)使用tcsetattr(3)进行更改。但请注意,stdio 在读取和写入终端设备时仍将使用行缓冲输入和输出;这也可以使用setvbuf(3)更改。