Dont't use scanf() when reading sentences

This tip submitted by Romnico on 2005-07-05 21:56:42. It has been viewed 70875 times.
Rating of 5.7 with 329 votes



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.



More tips

Help your fellow programmers! Add a tip!