Why does the message print twice?

后端 未结 4 1332
灰色年华
灰色年华 2021-01-15 01:29

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 fo

4条回答
  •  情歌与酒
    2021-01-15 01:58

    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.

提交回复
热议问题