忽略狼吞虎咽,只scanf函数(GCC)的返回值 [英] Ignore return value of a gobble-only scanf (gcc)

查看:200
本文介绍了忽略狼吞虎咽,只scanf函数(GCC)的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我读过​​这个问题以及其他相关的问题,我知道它的检查是一个好主意 scanf函数的返回值,以避免意外。
但是,我有我的code以下 scanf函数

So I've read this question and other related questions, and I know that it's a good idea to check the return value of scanf to avoid surprises. But I have the following scanf in my code:

/*
 * If we don't gobble newlines,
 * then they'll be interpreted as commands.
 * Gobble both \n and \r (because the input files use 0x0D).
 */
(void) scanf("%*[\n\r]");

正如你所看到的,我铸造 scanf函数的结果无效,但GCC仍在警告 -ansi -pedantic -Wall -O3 ,如上所述的>。

As you can see, I'm casting the result of scanf to void, but GCC still warns under -ansi -pedantic -Wall -O3, as noted here.

有什么干净的,我可以做燮preSS这一警告没有具体的编译器指令—也就是说,在纯粹的ANSI C90?
(通过清洁我的意思是没有如果(scanf函数(...)); 或类似)

Is there anything clean I can do to suppress this warning without compiler-specific directives—that is, in pure ANSI C90? (By clean I mean no if (scanf(...)); or similar.)

推荐答案

GCC 4.4并警告在这种情况下,但4.7和4.9不。该线与在海湾合作委员会的错误索赔您链接,它固定在4.5。因此,一个选择是使用编译器不到五岁的一个版本。

GCC 4.4 does warn in this case, but 4.7 and 4.9 do not. This lines up with the claim in that GCC bug you linked that it was fixed in 4.5. So one option is to use a version of the compiler less than five years old.

如果你坚持用GCC 4.4或以上,你可以这样做:

If you're stuck with GCC 4.4 or older, you can do this:

int dummy = scanf("%*[\n\r]");
(void)dummy;

这应该是一个熟悉的模式很多C或C ++程序员。

This should be a familiar pattern to many C or C++ programmers.

如果由于某种原因,你反对使用两个语句,并且不希望创建由@ PM100提出的忽略()功能,你也可以这样做:

If for some reason you object to using two statements and don't want to create an ignore() function as suggested by @pm100, you could also do this:

abs(scanf("%*[\n\r]"));

我更preFER的(无效)虚解决方案虽然。

最后,你可以避开 scanf()的干脆做这样的事情(未经测试,不是100%肯定它做你的需要):

Finally, you could avoid scanf() altogether and do something like this (untested, not 100% sure it does what you need):

int ch;
do {
  ch = getchar();
} while (ch == '\r' || ch == '\n');
ch = ungetc(ch, stdin);
assert(ch != EOF);

显然,你会把所有的在一个可爱的小功能,用描述性的名称,这可能是与 scanf函数是一个好主意()的解决方案了。

这篇关于忽略狼吞虎咽,只scanf函数(GCC)的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆