C语言怎么解决scanf()把回车作为输入值的问题
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>
int main()
{
int i = 0;
printf("scanf...\n");
char scanf_content[256] = {0};
scanf("%s", scanf_content);
printf("value: %s\n", scanf_content);
while (scanf_content[i])
{
if (scanf_content[i] == '\n')
printf("\\n");
else
printf("%d\n", (int)scanf_content[i]);
++i;
}
i = 0;
printf("gets...\n");
char gets_content[256] = {0};
gets(gets_content); // unsafe
printf("value: %s\n", gets_content);
while (gets_content[i])
{
if (gets_content[i] == '\n')
printf("\\n");
else
printf("%d\n", (int)gets_content[i]);
++i;
}
i = 0;
printf("fgets...\n");
char fgets_content[256] = {0};
fgets(fgets_content, 256, stdin);
printf("value: %s\n", fgets_content);
while (fgets_content[i])
{
if (fgets_content[i] == '\n')
printf("\\n");
else
printf("%d\n", (int)fgets_content[i]);
++i;
}
return 0;
}
输入“123 123”,你会发现scanf只会得到123,而gets可以得到空格123。最后fgets可以得到'\n'。这里为了看到空格和回车,可以把字符窜转成int打印出来。
最后的结论就是,如果需要回车,就使用fgets。