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?

3
  • 2
    One of the hundreds of duplicates of this question can be found here. Commented Oct 8, 2016 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? Commented Oct 9, 2016 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 <space><space><space>%c and <space>%c outputs the same stuff. Commented Oct 10, 2016 at 11:31

1 Answer 1

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); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.