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

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

问题描述

我创建一个简单的井字为C,这里是我有一个问题,一个特定的功能。这应该让用户选择'X'或'O',并为它的工作原理是最艺术。但是,如果我输入了错误的标志,它打印语句:
无效的符号,请重新输入的两倍。

为什么和如何我能解决这个问题?

 字符分配(无效)
{
      字符的用户;      的printf(你想为X或O(输入您的选择):);
      用户=的getchar();
      而(USER ='X'和;!&安培;用户='X'和;!&安培;用户='O'和;!&安培;!USER ='O')
      {
             的printf(无效的符号,请重新输入:);
             用户=的getchar();
      }
      如果(用户=='O'||用户=='O'),回报('O');
      否则,如果(用户=='X'||用户=='X')回报('X');
}


解决方案

这是因为当你使用的getchar 它返回的下一个字符,但保留换行符输入缓冲区。所以接下来的的getchar 返回换行符。

您也应该小心,因为的getchar 实际上返回一个 INT ,而不是字符

您可以解决这个问题或者通过另一个的getchar ,或使用 scanf函数是这样的:

  scanf函数(%C,&安培;用户);

请注意在 C 上述格式的空间,它告诉 scanf函数阅读并无视尾随空白。

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

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');     
}

解决方案

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.

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

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

scanf("%c ", &user);

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

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天全站免登陆