我有以下代码:
struct punto richiedi_punto () {
static int count=1;
struct punto point;
do {
printf("Inserire coordinate del punto %i:", count);
scanf("%d;%d",&point.x,&point.y);
} while (point.x<0 || point.x>9 || point.y<0 || point.y>9);
count++;
return point;
}
Gcc 未发现错误,但我收到此警告:
Warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
我试图在谷歌上找到解决方案,但我不明白是什么导致了这个警告。
提前致谢。
编辑:我刚才注意到,如果我在 MonoDevelop 控制台中运行我的程序,我无法插入我的坐标(为什么?),但如果我在 gnome-terminal 中运行它,它可以正常工作。
最佳答案
看看 scanf manual : 函数的返回值是您知道函数是否成功的唯一途径。
在这里,您的编译器不喜欢您的代码,因为您甚至不查看返回值,因此即使函数失败,您的代码也会继续。
这里很容易失败,例如,如果输入不是数字,或者不包含“;”正如预期的那样,或其他。
所以只需用类似的东西替换 scanf 行:
if (scanf("%d;%d",&point.x,&point.y) != 2)) {}
应该让 Gcc 放心,向他表明您关心返回值。 但最干净的解决方案是存储返回值并根据以下内容做一些事情,查看手册的“返回值”部分以获取更多信息。
关于c - scanf 函数的问题 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29430686/