C语言 scanf(" %[^\n]", str); 在 C 编程工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40038538/
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 10:30:18  来源:igfitidea点击:

How does scanf(" %[^\n]", str); work in C Programming?

cstring

提问by Joy Ram Sen Gupta

I encountered this in a C program:

我在 C 程序中遇到过这个:

char str[100];
scanf(" %[^\n]", str);

Please explain how it works and why?

请解释它是如何工作的以及为什么?

回答by

This scanfformat string consists of two parts:

scanf格式字符串由两部分组成:

  • a space character, which skips space characters (' ', '\t', '\n', etcetera) in the input, and
  • the %[^\n]conversion specification, which matches a string of all characters not equal to the new linecharacter ('\n') and stores it (plus a terminating '\0'character) in str.
  • 空格字符,其中跳过空格字符(' ''\t''\n'在输入,等等),和
  • %[^\n]转换规格,其中所有字符的字符串匹配不等于所述新行字符('\n'它(加上终止),并存储'\0'字符)的str

Note however that if the input (after the leading spaces, and before the first newline character) is longer than 99 characters, this function exhibits undefined behaviour, because strcan only hold 100 chars including the terminating '\0'character. A safer alternative is:

但是请注意,如果输入(在前导空格之后,第一个换行符之前)超过 99 个字符,则此函数表现出未定义的行为,因为包括终止字符在内str只能保持 100char'\0'。一个更安全的选择是:

scanf(" %99[^\n]", str);

回答by Atal Kishore

[^\n]searches for line break

[^\n]搜索换行符

hence it will scan for the string until enter is pressed

因此它将扫描字符串直到按下输入