![](/img/trans.png)
[英]What does the format string “%*[^\n]” in a scanf() statement instruct? How do assignment suppressor (*) and negated scanset ([^) work together?
[英]For scanf(), why is negated scanset “%[^\n]” showing correct output for “\n”, but not the scanset “%[aeiou]” for “aegis”?
在下面的程序中,如果我使用该行作为否定的扫描集,即使输入的是多行(以ENTER或换行结尾),即使换行在否定列表中,它也可以正常工作。
但是,如果我改用该行作为scanset并输入单词“ aegis”(或与此有关的任何带有辅音的单词),则会输出垃圾字符。 与第一种情况类似,如果我输入此单词,至少不应输出“ ae”吗? 请解释一下scanset的行为以及scanf()否定的scanset的行为。
#include <stdio.h>
int main ()
{
char str[30];
printf("Enter the string\n");
//scanf("%[^\n]",str);
//scanf("%[aeiou]",str);
printf("%s",str);
}
这是因为代码错误地不检查scanf()
的返回值
printf("Enter the string\n");
scanf("%[^\n]",str);
scanf("%[aeiou]",str); // check result before using `str`
printf("%s",str);
使用scanf("%[^\\n]",str);
并输入"123\\n"
, str
获得值"123"
并且'\\n'
保留在stdin
。 然后用scanf("%[aeiou]",str);
并输入"aegis\\n"
,第一行的'\\n'
阻止保存任何内容,因为'\\n'
不是元音,因此在str
中未保存任何内容,并且由于代码未检查scanf()
的返回值,因此不会意识到str
可能无效。
1)始终检查scanf()
和family的返回值。
if (scanf(some_format, var1, var2, ...) != ExpectedConversionCount) {
Fail();
}
2) scanf("%[^\\n]",str);
读取行失败3件事:没有输入限制,如果行仅由'\\n'
组成,则无法读取任何内容。 如果不检查返回值,则不会检测到EOF
。
3)使用fgets()
代替scanf()
进行用户输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.