1

I am learning by myself how to code using the C languange. In order to study this latter a bit more in depth, I'm doing some basic exercises and, due to this, today I have faced a little issue using the scanf() instruction. Infact, the following code:

int main() {

  char inputOne;
  char inputTwo;

  printf("Insert a char: ");
  scanf("%c", &inputOne);
  // &inputOne is the pointer to inputOne.

  printf("Insert another char: ");
  scanf("%c", &inputTwo);

  if (inputOne == inputTwo) {
    printf("You have inserted the same char!\n");
    printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
  } else {
    printf("You have inserted two different chars!\n");
    printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
  }

}

when compiled does not return any error, but when I launch the application on the Terminal, I am not able to insert the second character. Here is an example of what happens:

Macbook-Pro-di-Rodolfo:~ Rodolfo$ /Users/Rodolfo/Documents/GitHub/Fondamenti\ di\ C/esempio-if-else ; exit;
Insert a char: a
Insert a second char: You have inserted two different chars!
Chars inserted: a, 

logout

[Process completed]

Can anybody explain me why this happens?

rudicangiotti
  • 566
  • 8
  • 20
  • 2
    One of the *hundreds* of duplicates of this question [can be found **here**](https://stackoverflow.com/questions/1959255/c-trying-to-read-a-single-char-from-stdin-and-failing-w-scanf-getchar). – WhozCraig Oct 08 '16 at 18:29
  • @user3121023 do the number of spaces before or after the conversion specification influence the final result? With other words, are `scanf(" %c", &inputTwo)` and `scanf(" %c", &inputTwo)` identical for the compiler? – rudicangiotti Oct 09 '16 at 23:21
  • @user3121023 I'm sorry, it is not properly visible in my first comment but I was meaning if `scanf()` behaves in the same way indipendently from the number of white spaces between the quotation mark and the conversion specification `%`. In other words, if `%c` and `%c` outputs the same stuff. – rudicangiotti Oct 10 '16 at 11:31

1 Answers1

1

It takes line feed as input to the second character. You can take the inputTwo again to prevent it:

int main() {

  char inputOne;
  char inputTwo;

  printf("Insert a char: ");
  scanf("%c", &inputOne);
  // &inputOne is the pointer to inputOne.

  printf("Insert another char: ");
  scanf("%c", &inputTwo);
  scanf("%c", &inputTwo);

  if (inputOne == inputTwo) {
    printf("You have inserted the same char!\n");
    printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
  } else {
    printf("You have inserted two different chars!\n");
    printf("Chars inserted: %c, %c\n", inputOne, inputTwo);
  }

}
shiva
  • 2,535
  • 2
  • 18
  • 32