Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the message print twice?

Tags:

c

while-loop

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');     
}
like image 500
C_Intermediate_Learner Avatar asked Feb 02 '26 04:02

C_Intermediate_Learner


1 Answers

The problem cause is related to the newline charachter

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

scanf(" %c", &user);
like image 158
MOHAMED Avatar answered Feb 04 '26 01:02

MOHAMED



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!