scanf and gets

please provide me link for the reason of the problem when we use scanf and gets simultaneously…

Hopefully this will help you -

1 Like

Depends on how you’re using it.

For example: If your code snippet is something like this

printf("Enter your roll number: ");
scanf("%d", &roll);

printf("Enter your name: ");

Here you won’t get desired result. Why? Because gets is reading only the ‘\n’ left by the scanf

You can rectify it by doing:

printf("Enter your roll number: ");
scanf("%d\n", &roll);

printf("Enter your name: ");

Now name will store the string that you will enter when prompted.

It is pretty simple, no rocket science. Do not make an assumption that there will always be a problem when you use both function simultaneously. If you know the mechanism of how they work then you will always use it in the right manner. Dennis Ritchie didn’t develop C to incorporate these basic I/O flaws. You need to learn it, in a more concrete manner.


sir, more link please!!!

Thanks for sharing :slight_smile:

may i know why there is always(or may be) new line character present in the input buffer?

@rudra_saraf >> Because after entering roll number will you hit the Enter or not for the next action to be prompted?

Similarly, in the input test cases there is a newline ‘\n’
For example

1 2 3