mardi 26 juillet 2016

Does Scanf function ignore the Enter key when looking for %d match?

I'm new to to C language and I'm studying it on a book by Kim N. King. It say that the scanf() looks for number pattern ignoring the whitespaces but I think it also skips on Enter key. While if it looks for characters it obviously takes the whitespace also.

Therefore in this example code I have to use getchar() to clear the stream before the second scanf(), otherwise the second one would be executed without waiting for user's input.

printf("Enter a char: ");
scanf("%c", &ch1);
getchar();
printf("nEnter another char: ");
scanf("%c", &ch2);

If I look for digits instead, I have no problems.

printf("Enter a number: ");
scanf("%d", &n1);
printf("nEnter another number: ");
scanf("%d", &n2);

Is my assumption (It skips the Enter key) right?

Aucun commentaire:

Enregistrer un commentaire