; %[^\ n]%*c"和&quot %[^\ n]"用于C中连续的canf

发布于 2025-01-26 04:52:32 字数 194 浏览 2 评论 0原文

我一直在尝试扫描多个连续的字符串。

我知道您必须消除Newline角色,并且我还被告知“%[^\ n]%*C”是正确的方法。 但是在我的测试中,“%[^\ n]”工作得更好,因为它更简单,而且如果我尝试直接喂食新线,也不会出错,它会不断等待字符串。 到目前为止,一切都很好。

有什么情况“%[^\ n]%*c”是更好的方法?

多谢!

I've been trying to scanf multiple consecutive strings.

I know you have to eliminate the newline character and i've also been told that "%[^\n]%*c" is the RIGHT way.
But in my tests, " %[^\n]" works even better because it's simpler and also doesn't go wrong if i try to feed it a newline directly, it keeps waiting a string.
So far so good.

Is there any case in which "%[^\n]%*c" is the better way?

Thanks a lot!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如梦亦如幻 2025-02-02 04:52:32

此格式字符串“%[^\ n]”允许跳过引导白色空格,包括新的行字符'\ n'通过以前的调用在输入缓冲区中存储在输入缓冲区中scanf

但是,如果您将使用fgetsscanf使用此类格式字符串的调用后,则fgets将读取一个空字符串,因为新行字符<代码>'\ n'将存在于输入缓冲区中。

在使用此格式字符串scanf调用后,“%[^\ n]%*c”您可以调用fgets,因为新行字符将被删除。

请注意这些格式字符串“%[^\ n]%*c”“%[^\ n]%*c”具有不同的效果。第一个不允许跳过与第二格式字符串相对的领先的白空间字符。

要调用SCANF更安全的呼叫,您应该指定一个长度修饰符

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

This format string " %[^\n]" allows to skip leading white spaces including the new line character '\n' stored in the input buffer by a previous call of scanf.

However if you will use fgets after a call of scanf with such a format string then fgets will read an empty string because the new line character '\n' will be present in the input buffer.

After a call of scanf with this format string "%[^\n]%*c" you may call fgets because the new line character will be removed.

Pay attention to that these format strings "%[^\n]%*c" and " %[^\n]%*c" have different effects. The first one does not allow to skip leading white space characters opposite to the second format string.

To make a call of scanf safer you should specify a length modifier as for example

char s[100];
scanf( " %99[^\n]", s );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文