首页 > 解决方案 > 忽略返回值(C 编程)

问题描述

几天前我刚开始学习 C 编程,我正在尝试从 Kattis (open.kattis.com) 网站上解决一些问题。我一路上遇到了这个问题,我真的不明白它的意思。

//two stones

#include <stdio.h>

int main()
{ 
int n,x=2;

printf("The number of stones placed on the ground is ");
scanf("%d",&n);

if (n%x != 0)
{
    printf("The winner of the game is Alice! \n");
}
else
{
    printf("The winner of the game is Bob! \n");
}
return 0;
}

这出现了>>

警告:忽略 scanf 的返回值,用关于 scanf("%d",&n) 的属性 warn_unused_result [-Wunused-result] 声明;

谁能解释这有什么问题以及如何解决这个问题?谢谢。

标签: c

解决方案


scanf有一个指示成功的返回值:

C标准;§7.19.6.4.3

如果在任何转换之前发生输入失败,scanf 函数将返回宏 EOF 的值。否则,scanf 函数会返回分配的输入项的数量,如果出现早期匹配失败,该数量可能会少于提供的数量,甚至为零。

如果您的调用中有一个具有一个格式说明符的格式字符串,那么您可以通过将其返回值与 1 进行比较scanf来检查是否scanf成功从 接收该类型的输入。stdin

你的编译器警告你这不是特别是因为scanf返回一个值,而是因为检查scanf. printf例如,符合标准的.


推荐阅读