0

I have a question, We were asked by our teacher to write a rock paper scissors program using the if else statement

my problem is

if i code it like this

char a, b;
clrscr();
printf("\n Enter player 1 value");
scanf("%c", &a);
printf("\n Enter Player 2 value:);
scanf("%c", &b);

my problem is when i code it like this after entering the 1st value it ignores the second one and just goes on the if statements

and i found a solution which is putting space on %c on the second scanf which looks like this (found a similar program)

scanf(" %c", &b);

and it works but now i don't know why ?? can anyone explain to me why it was being ignored and why putting a space solves that problem ?? it will gladly help

thanks in advance

Shai
  • 25,159
  • 9
  • 44
  • 67
  • 2
    Perhaps read the manual page for `scanf` It does return a value and describes how it works – Ed Heal Jul 26 '15 at 09:08
  • alright thanks for the response – Domenic Escobedo Jul 26 '15 at 09:23
  • You enter a character and press enter. The character you typed gets consumed by the first `scanf` and the newline character generated by the enter key press gets consumed by the second `scanf`. Space is considered as a whitespace character and a whitespace character in `scanf` instructs `scanf` to scan any number of whitespace characters, including none, until the first non-whitespace character. – Spikatrix Jul 26 '15 at 09:40

2 Answers2

0

by adding a space you exclude the whitespaces created by the previous scanf.

RatikBhat
  • 61
  • 11
0

scanf() stops as soon it finds a whitespace so if the string start with a whitespace you get nothing.

use scanf("%[^\n]", &variable) to get everything (space included) or even better scanf("%30[^\n]", &variable) to get everything with a size limit on the input (in this case 30).

There is also another function that lets you read from a stream: fgets(&variable, sizeof variable, stdin); check the doc out here(http://www.cplusplus.com/reference/cstdio/fgets/)

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36