Monday, May 16, 2011

Don’t use scanf() when reading sentences

If we use this code:

printf("ENTER SENTENCE: "); scanf("%s",string);
printf("string is =%s",string);


And if we run it and type a sentence:

ENTER SENTENCE: This sentence.

The output would be: "string is =This"

A second reason to avoid using scanf with strings is that it allows someone to enter too much text and thereby overflow the buffer. The best choice for reading in strings is to use fgets as described in this explanation the problems with gets.