如何在视觉工作室中修复"return value ignored: 'scanf'"代码C6031



我是编码C(以及一般编码(的新手,所以我一直在练习一些随机程序。这个应该根据用户的年龄和所需的"区域"数量(他们想走多远(来确定交通票的成本(Translink Vancouver价格(。我已经成功编译了它,但由于某种我无法弄清楚的原因,scanf 函数被忽略了。我该如何解决这个问题?请记住,我只编码了几天。谢谢!

int main(void) {
int zones;
int age;
double price = 0.00;
printf("Welcome to TransLink cost calculator!nn");
printf("Please enter the desired number of zones (1, 2, or 3) you wish to travel: ");
scanf("%d", &zones);
if (zones < 1) {
printf("Invalid entryn");
price = 0.00;
}
else if (zones > 3) {
printf("Invalid entryn");
price = 0.00;
}
else if (zones == 1) {
printf("Please enter your age: ");
scanf("%d", &age);
if (age < 0.00) {
printf("Invalid Aage");
}
else if (age < 5) {
price = 1.95;
}
else if (age >= 5) {
price = 3.00;
}
}
else if (zones == 2) {
printf("Please enter your age: ");
scanf("%d", &age);
if (age < 0) {
printf("Invalid Aage");
}
else if (age < 5) {
price = 2.95;
}
else if (age >= 5) {
price = 4.25;
}
}
else if (zones == 3) {
printf("Please enter your age: ");
scanf("%d", &age);
if (age < 0) {
printf("Invalid Aage");
}
else if (age < 5) {
price = 3.95;
}
else if (age >= 5) {
price = 4.75;
}
}
printf("The price of your ticket is: $%.2f + taxn", price);
system("PAUSE");
return 0;
}

这里有点太多了,无法发表评论。

我使用Visual C的一个版本,但它从不抱怨未使用scanf的返回值。它所做的是抱怨scanf不安全和弃用,而事实并非如此。

MS 认为我应该使用它自己的"更安全"的版本scanf_s它使用起来更棘手,而且 IMO 一点也不安全——因为它不是同类替代品,而是采用不同的论点,因此在使用时很容易出错。

随之而来的一个问题是编译器每次使用scanf(和其他一些函数(时都会发出警告,这会掩盖其他警告。我按照建议处理它,在第一个库标头包含之前添加一个#define

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

MS还警告其他事项,我实际上在每个文件的开头放置了三个#defines

#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE  
#define _CRT_NONSTDC_NO_DEPRECATE
#include <stdio.h>

现在,相关警告很容易看到。

来自scanf()的文档(例如 https://en.cppreference.com/w/c/io/fscanf(

返回值
1-3( 成功分配的接收参数数(如果在分配第一个接收参数之前发生匹配失败,则可能为零(,如果在分配第一个接收参数之前发生输入失败,则为 EOF。

您忽略了该返回值。

取代

scanf("%d", &age);

int NofScannedArguments=0; /* Number of arguments which were
successfully filled by the most recent call to scanf() */
/* ...  do above once, at the start of your function */
NofScannedArguments= scanf("%d", &age);
/* check the return value to find out whether scanning was successful */
if(NofScannedArguments!=1) /* should be one number */
{
exit(EXIT_FAILURE); /* failure, assumptions of program are not met */
}

。以了解扫描是否成功。 不这样做是一个坏主意,值得你得到警告。

如果您想更优雅地处理故障,例如再次提示用户,
请使用循环并阅读有关您可能遇到的陷阱 http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html。
我并不是说你不应该使用 scanf,这篇文章解释了很多关于使用 scanf 的信息,同时试图说服你不要这样做。

使用 C++ 函数进行输入要容易得多。 代替scanf和printf,可以使用cin和cout,如下所示:

#include <iostream>  // for cin and cout use
int main()
{
int zones;
std::cout << "Enter zones" << std::endl;  // endl is similar to n
std::cin >> zones;
std::cout << "Your zones is " << zones << std::endl;
}

最新更新