C语言 scanf 读取“Enter”键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19794268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:53:24  来源:igfitidea点击:

scanf reading "Enter" key

cscanfcarriage-return

提问by vs06

Why scanf doesn't work when I type "Enter" in the code below?

为什么当我在下面的代码中输入“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);
}

回答by chux - Reinstate Monica

The "%s"in scanf("%s",...skips over leading whitespace (including "Enter" or \n) and so patiently waits for some non-whitespace text.

"%s"scanf("%s",...对领导空格跳跃(包括“回车”或\n)等耐心地等待一些非空白文本。

Best to take in a \n, use fgets()as suggested by @maxihatop

最好按照@maxihatop 的建议\n使用a ,使用fgets()

fgets(msg, 100, stdin);

If you needto use scanf()

如果您需要使用scanf()

int result = scanf("%99[^\n]%*c", msg);
if (result != 1) handle_IOError_or_EOF();

This will scan in 1 to 99 non-\nchars and then append a \0. It will then continue to scan 1 more char(presumably the \n) but not save it due to the *. If the first character is a '\n', msgis not changed and the '\n'remains in stdin.

这将扫描 1 到 99 个非\n字符,然后附加一个\0. 然后它将继续扫描 1 个char(大概是\n),但由于*. 如果第一个字符是'\n',msg则不会改变,而'\n'保留在stdin.



Edit (2016): To cope with lines that begin with '\n', separate the scan that looks for the trailing '\n'.

编辑(2016 年):要处理以 开头的行,'\n'请将查找尾随的扫描分开'\n'

msg[0] = '
fgets(msg, 100, stdin);
'; int result = scanf("%99[^\n]", msg); scanf("%*1[\n]"); if (result == EOF) handle_IOError_or_EOF();

回答by olegarch

Because of scanf() wait char-string, separated by whitespaces, enters, etc. So, it just ignores ENTERs, and waiting for "real non-empty string". If you want to get empty string too, you need to use

由于 scanf() 等待字符字符串,由空格分隔,输入等。因此,它只是忽略 ENTER,并等待“真正的非空字符串”。如果你也想得到空字符串,你需要使用

##代码##

回答by PandaRaid

Scanf looks through the input buffer for the specified format, which is string in this case. This has the effect of skipping your whitespaces. If you put a space between wording, it skips the space looking for the next string, similarly it will skip tabs, newlines etc. See what happens if you put a %c instead. It will pick up the newline because it is searching for a char now, and '\n' constitutes as a valid char.

Scanf 在输入缓冲区中查找指定格式,在本例中为字符串。这具有跳过空格的效果。如果你在措辞之间放置一个空格,它会跳过寻找下一个字符串的空格,类似地它会跳过制表符、换行符等。看看如果你放一个 %c 会发生什么。它将拾取换行符,因为它现在正在搜索一个字符,并且 '\n' 构成一个有效的字符。

If you want the same effect while getting whitespace, change it to a %c and remove the newline escape character at the print statement.

如果在获取空格时想要相同的效果,请将其更改为 %c 并删除打印语句中的换行符转义字符。