scanf()是不会把回车拷贝到字符窜里面的。
这里是一段英文定义: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace).
除了回车,空格也不会拷贝到字符窜中。
再来看下gets(),英文定义是这样的:Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str.
好了。这里写的很清楚了。gets()虽然可以把输入都拷贝到字符窜里,比如空格,但是不包含回车。
如果需要回车,可以用fgets()。英文是这样定义的:Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
最后一句话说了,回车作为结束,不过会拷贝到字符窜中。
那么文档说的对不对呢?写一段代码测试一下。
#include <stdio.h>输入“123 123”,你会发现scanf只会得到123,而gets可以得到空格123。最后fgets可以得到'\n'。这里为了看到空格和回车,可以把字符窜转成int打印出来。
最后的结论就是,如果需要回车,就使用fgets。
为什么用scanf不可以?