What are options scanf vs gets vs fgets?

470 views Asked by At

I heve a following code

while ( a != 5)
 scanf("%s", buffer);

This works well but takes no space in between the mentioned words or in other words, scanf terminates if we use spaces to scan

If I use this

while( a != 5)
 scanf("%[^\n]", buffer);

It works only for once which is bad

I never use gets() because I know how much nasty it is..

My last option is this

while( a != 5)
  fgets(buffer, sizeof(buffer), stdin);

So my questions are

  1. Why the second command is not working inside the loop?
  2. What are the other options I have to scan a string with spaces?
2

There are 2 answers

2
AzNjoE On BEST ANSWER

"%[^\n]" will attempt to scan everything until a newline. The next character in the input would be the \n so you should skip over it to get to the next line.

Try: "%[^\n]%*c", the %*c will discard the next character, which is the newline char.

2
Sourav Ghosh On

Why the second command is not working inside the loop

Becuase, for the first time what you scan until \n, the \n is remaining in the input buffer. You need to eat up (or, in other word, discard) the stored newline from the buffer. You can make use of while (getchar()!=\n); to get that job done.

What are the other options I have to scan a string with spaces?

Well, you're almost there. You need to use fgets(). Using this, you can

  1. Be safe from buffer overrun (Overcome limitation of gets())
  2. Input strings with spaces (Overcome limitation of %s)

However, please keep in mind, fgets() reads and stores the trailing newline, so you may want to get rid of it and you have to do that yourself, manually.