为什么消息打印两次? [英] Why does the message print twice?

查看:38
本文介绍了为什么消息打印两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 C 创建一个简单的 Tic Tac Toe,这是一个我遇到问题的特定函数.这应该让用户选择X"或O",并且对于大多数艺术作品来说都是如此.但是,如果我输入了错误的符号,它会打印以下语句:无效符号,请重新输入:"两次.

I am creating a simple Tic Tac Toe for C, and here is a particular function which I am having a problem with. This is supposed to let the user select 'X' or 'O', and for the most art it works. However, if I enter a wrong symbol, it prints the statement: "Invalid symbol, please re-enter: " twice.

为什么以及如何解决这个问题?

Why and how can I fix this?

char assign(void)                                 
{
      char user;

      printf("Would you like to be X or O (Enter your choice): ");
      user=getchar();
      while(user != 'X' && user != 'x' && user != 'O' && user != 'o')
      {
             printf("Invalid symbol, please re-enter: ");  
             user=getchar();
      }
      if(user == 'O' || user == 'o')        return('O');
      else if(user == 'X' || user == 'x')   return('X');     
}

推荐答案

这是因为当您使用 getchar 时,它返回下一个字符,但将换行符留在输入缓冲区中.所以下一个 getchar 返回那个换行符.

It's because when you use getchar it returns the next character, but leaves the newline in the input buffer. So the next getchar returns that newline.

你也应该小心,因为 getchar 实际上返回的是 int 而不是 char.

You should also be careful because getchar actually returns an int and not a char.

你可以通过另一个 getchar 解决这个问题,或者像这样使用 scanf:

You can solve this either by another getchar, or use scanf like this:

scanf("%c ", &user);

注意上面格式中 c 后面的空格,它告诉 scanf 读取并忽略尾随空格.

Note the space after the c in the above format, it tells scanf to read and disregard trailing whitespace.

您也可以阅读一行,例如fgets 然后在该行上使用一个简单的 sscanf,则不需要额外的空间.

You could also read a line with e.g. fgets and then use a simple sscanf on that line, then no extra space is needed.

这篇关于为什么消息打印两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆