Reputation: 566
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?
Upvotes: 1
Views: 128
Reputation: 2709
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);
}
}
Upvotes: 1