Why does the message print twice?

匆匆过客 提交于 2019-12-01 09:25:57

问题


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

回答1:


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.




回答2:


The problem cause is related to the newline charachter

use scanf() in this way instead of using getchar()

scanf(" %c", &user);



回答3:


You could fix it like this for example:

char assign(void)
{
      char user;
      char throwaway_newline;

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



回答4:


You have a newline in your input buffer.

When you press a character which is not [xX] and not [oO] and follow it with a newline. getchar actually gets to see 2 characters(the newline and the invalid character)

You may want to use fgets instead of relying on character input and ignoring newlines with 2 getchar() calls everytime.



来源:https://stackoverflow.com/questions/17898412/why-does-the-message-print-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!