scanf("%c", &var); and scanf("%c", &var); the difference between (the former has no space after the format specifier; the latter has a space after the format specifier)

Asked 2 years ago, Updated 2 years ago, 28 views

int main() { char var_1, var_2; scanf("%c", &var_1); printf("%c\n", var_1); scanf("%c", &var_2); // Add space after format specifier printf("%c\n", var_2); }

/* while studying C language "Use scanf("%c", &var); to receive characters. You need to insert a space in the format specifier The new line character is removed." It's written in the book, but I don't know the difference. And if there's a difference, can anyone tell me why such a difference occurs? */

c

2022-09-22 19:39

1 Answers

scanf() receives input using an input buffer when receiving text, in the form of a format specifier Only characters are read from the input buffer.

The type of enter that you pressed to indicate that you are completing the input, i.e. \n, the character you mentioned as a new line character, remains in the input buffer.

If you call scanf() again in this state, \n remaining in the input buffer is read, so you cannot receive proper input

To prevent this, I wrote down to remove the new line character by adding spaces to the format specifier, but I'm not sure if it's actually being removed.


2022-09-22 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.