gpt4 book ai didi

c - scanf ("%s", str) 和 scanf ("%[^\n]s", str) 返回值的区别

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:08 32 4
gpt4 key购买 nike

while(scanf("%s",a))
{
if(a[0]=='#')
break;
nextpermutation(a);
}

这个 while 循环完全适用于 scanf("%s", a)但是如果我将 scanf("%[^\n]s", a) 放在 while 中,它只会运行一次。我检查了两个 scanf 的返回值,它们仍然相同。我不明白为什么会这样......

最佳答案

两个失败者的战斗:"%s" vs. "%[^\n]s":

这两个说明符都是不好的,不属于健壮的代码。既不会限制用户输入,也不会轻易溢出目标缓冲区。

"%[^\n]s" 中的 s 没有任何作用。 @Jonathan Leffler .所以 "%[^\n]" 被审查如下 - 仍然很糟糕。

"%s" 占用前导空白。 "%[^\n]" 不是 @Igor Tandetnik

如果前导字符是 '\n'

"%[^\n]" 将读取nothing,留下 a 未更改或很少处于未知状态。

"%[^\n]" 读取除 '\n' 之外的所有字符。

"%s" 读取所有前导空白,丢弃它们,然后读取并保存所有非空白。


最好使用 fgets() 读取用户输入的,然后对其进行解析。

示例:读取一行输入,包括空格:

char a[100];
if (fgets(a, sizeof a, stdin) == NULL) Handle_EOF_or_Error();

// if the potential trailing \n is not wanted
a[strcspn(a, "\n")] = '\0';

关于c - scanf ("%s", str) 和 scanf ("%[^\n]s", str) 返回值的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40693495/

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