为什么我的C代码重复第一个printf行?
我想要一个无限循环,这很有效。但我不知道为什么它会打印出同一行两次。有什么想法吗?
输出:
最后选择:p
您的下一步行动:R最后的选择:最后的选择:l
最后选择: 最后选择: r
你的下一步行动:S最后的选择:最后的选择:
这是我到目前为止的代码:
#include <stdio.h>
#include <cs50.h>
int main ()
{
while (true)
{
// Prompt user for input last choice contender
char c;
printf("Last choice: ");
c = getchar();
// If last choice is R, loser should play S
if (c == 'R'|| c == 'r')
{
printf("Your next move: S");
}
// Else if last choice is P, loser should play R
else if (c == 'P' || c == 'p')
{
printf("Your next move: R");
}
// Else if last choice is S, loser should play P
else if (c == 'S' || c == 's')
{
printf("Your next move: P");
}
}
}
I want an infinite loop and that's working. But I don't know why it prints out the same line two times. Any thoughts?
The output:
Last choice: p
Your next move: RLast choice: Last choice: l
Last choice: Last choice: r
Your next move: SLast choice: Last choice:
This is my code so far:
#include <stdio.h>
#include <cs50.h>
int main ()
{
while (true)
{
// Prompt user for input last choice contender
char c;
printf("Last choice: ");
c = getchar();
// If last choice is R, loser should play S
if (c == 'R'|| c == 'r')
{
printf("Your next move: S");
}
// Else if last choice is P, loser should play R
else if (c == 'P' || c == 'p')
{
printf("Your next move: R");
}
// Else if last choice is S, loser should play P
else if (c == 'S' || c == 's')
{
printf("Your next move: P");
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为当你输入密钥然后按 Enter 时,getchar 会正确获取你的密钥,并且它还会获取一个
\n
这是你的 Enter 键。因此,您只需要在代码中添加一点 if 即可使其像这样工作:It's because when you put your key and then press enter, getchar gets your key right, and it also gets a
\n
which is your enter key. So you just need to add on a little if in your code to make it work like this:我想我已经为你工作了!
I think I got it working for you!
我希望您能得到答案,如果没有,让我帮助您。
看到您正在使用 getchar 它从输入缓冲区读取字符,但是,当 while 重新读取时,它会读取缓冲区中剩余的字符两次,其他则会读取新行自动地。
为了解决这个问题,我们可以使用 fflush(stdout) 来刷新输出缓冲区,并使用 flush(stdin) 在读取输入之前刷新输入缓冲区。
如何在您的代码中使用它们?
就在 printf("last choice") 之后和 c=getchar() 之前,将其像代码中所示
希望这有帮助,请告诉我!
I hope you got your answer, if not let me help you with how.
See you are using getchar it reads characters from the input buffer, however, when while rereads it reads two times once for characters left in the buffer and other it reads the new line automatically.
To solve this we can use fflush(stdout) this flushes out output buffer and flush(stdin) flushes input buffer before reading input.
How to use them in your code?
Just after printf("last choice")and before c=getchar() put it like this as shown in code
Hope this helps please let me know!