>>>%s\n", str); 这是我的理解: 第一部分 "[^\n]"表示接受除 '\n' 之外的任何字-6ren">
gpt4 book ai didi

无法弄清楚 C 语言中 scanf ("%[^\n]\n", input) 会发生什么

转载 作者:行者123 更新时间:2023-12-04 10:09:15 26 4
gpt4 key购买 nike

char str[20];
scanf("%[^\n]\n", str);
printf(">>>>%s\n", str);

这是我的理解:
第一部分 "[^\n]"表示接受除 '\n' 之外的任何字符,以便从函数 scanf 中获取某些字符,例如空格并将其存储在 str 中。
第二个\n 用于匹配结束 scanf 的\n,否则\n 将在输入流中释放并留给下一个输入操作。

但是当我运行它时,结果让我感到困惑。
xhkjdeiMac:c xhkj$ ./hello
aaaaaaa
ccc
>>>>aaaaaaa

如您所见,我首先输入 aaaaaaa 并按回车键,我认为它将 aaaaaa 存储到 str 中并且已经匹配了\n。但是我必须输入其他内容,例如 ccc,然后才能进行下一步并在控制台上打印 str 。

那么为什么会发生呢?为什么我必须输入其他内容并再次按回车键才能完成扫描?

最佳答案

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

OP: the first part "[^\n]" means accepting any character except '\n' in order to obtain some character, .... and store it in str.



不完全的。

如果读取的第一个字符是 '\n' , 扫描停止。 str 中没有保存任何内容, 不附加空字符, '\n'留在 stdin和函数返回 0 或 EOF(我忘记了,但它不是 1)

否则非 '\n'字符被读取并保存,直到 '\n'已读。那个 '\n'被放回 stdin , 一个空字符附加到 str .扫描继续格式 "\n" .如果读取了 20 个或更多字符,则会导致未定义的行为。

主要问题

OP: The second \n is for match the \n which ends the scanf, otherwise the \n will release in input stream and left to next input action.



编号格式 "\n"匹配任意数量的空格,而不仅仅是 1 '\n' . scanf()消耗空白,如 '\n' , ' ' , '\t' , ..., 直到读取到非空白字符。然后将该非空白字符放回 stdin .

OP: why should I have to enter something else and hit the enter key again to finish the scanf?



程序在返回之前等待的是一个非空白字符。自 stdin通常是行缓冲的,非空白字符不会提供给 scanf()直到它有以下 '\n' .
scanf("%[^\n]\n", str);是有问题的。使用 fgets() .检查返回值。
char str[20];
if (fgets(str, sizeof str, stdin)) {
str[strcspn(str, "\n")] = '\0'; // lop off potential trailing \n if desired
printf(">>>>%s\n", str);
}

如果有,叹,必须用 scanf() , 考虑:
*str = 0;              // Handle case when first letter is \n
scanf("%19[^\n]", str);// Consume up to 19 characters
scanf("%*1[\n]"); // Consume 1 \n if present-independent of success of previous

关于无法弄清楚 C 语言中 scanf ("%[^\n]\n", input) 会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60372993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com