scanf() VS gets()

The chief difference between scanf() and gets() lies in how they decide when have reached the end of the string: scanf() is more of a "get word" than a "get string" function. The gets() function, as you've seen, takes in all the characters up to the first newline. The scanf() function has two choices for terminating input. For either choice, the string starts at the first non-whitespace character  encountered. If you use the %s format, the string runs up to (but not including) the next whitespce character (blank, tab, or newline). If you specify a field width, as in %10s, the scanf() collects up to 10 characters or up to the first whitespace character, whichever comes first.

Depending on the nature of the desired input, you may be better off using gets() to read text from the keyboard. It is easier to use, faster, and more compact. The typical use for scanf() is reading and converting a mixture of data types in some standard form. For example, if each input line contains the name of a tool, the number in stock, and the cost of the item, you might use scanf(), or you might throw together a function of your own that does some entry error-checking. If you want to process input a word at a time, you can use scanf().


你可能感兴趣的:(scanf() VS gets())