为什么我在下面的代码中输入“Enter”时scanf不起作用?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char**argv)
{
char *msg = malloc(100*sizeof(char));
do{
scanf("%s",msg);
printf("%s\n",msg);
} while(strcmp(msg,"")!=0);
}
最佳答案
scanf("%s",...
中的 "%s"
跳过前导空格(包括 "Enter"或 \n
),所以耐心地等待一些非空白文本。
最好接受一个\n
,使用fgets()
。
char msg[100];
if (fgets(msg, sizeof msg, stdin)) {
// success
如果你需要使用scanf()
int result = scanf("%99[^\n]%*c", msg);
if (result != 1) handle_rump_line_or_end_of_file_or_IOError();
这将扫描 1 到 99 个非 \n
字符,然后附加一个 \0
。然后它将继续扫描另外 1 个 char
(可能是 \n
),但由于 *
而不会保存它。如果第一个字符是 '\n'
,则 msg
不会更改,'\n'
仍保留在 stdin
.
编辑 (2016):为了处理以 '\n'
开头的行,将查找尾随 '\n'
的扫描分开。
msg[0] = '\0';
int result = scanf("%99[^\n]", msg);
scanf("%*1[\n]");
if (result == EOF) handle_end_of_file_or_IOError();
关于c - scanf 读取 "Enter"键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794268/