为什么我的程序不响应任何参数? 我有一个简单的C++程序,打印出圆的属性 #include <iostream> #include <stdlib.h> #include "circle.h" // contains the Circle class using namespace std; void print_circle_attributes(float r) { Circle* c = new Circle(r); cout << "radius: " << c->get_radius() << endl; cout << "diameter: " << c->get_diameter() << endl; cout << "area: " << c->get_area() << endl; cout << "circumference: " << c->get_circumference() << endl; cout << endl; delete c; } int main(int argc, const char* argv[]) { float input = atof(argv[0]); print_circle_attributes(input); return 0; }

为什么我的程序不响应任何参数? 我有一个简单的C++程序,打印出圆的属性 #include <iostream> #include <stdlib.h> #include "circle.h" // contains the Circle class using namespace std; void print_circle_attributes(float r) { Circle* c = new Circle(r); cout << "radius: " << c->get_radius() << endl; cout << "diameter: " << c->get_diameter() << endl; cout << "area: " << c->get_area() << endl; cout << "circumference: " << c->get_circumference() << endl; cout << endl; delete c; } int main(int argc, const char* argv[]) { float input = atof(argv[0]); print_circle_attributes(input); return 0; },c++,command-line-arguments,argv,C++,Command Line Arguments,Argv,我以前测试过这个程序,没有参数,只是简单地使用静态值,它运行得很好;所以我知道我上的课没什么问题 那么我在这里做错了什么呢?argv[0]是被调用的可执行文件的名称 您的第一个命令行参数将位于argv[1]中 为了确保您的程序不会再次以静默方式失败,您应该检查实际有多少个参数,以及atof是否返回值,并向用户显示相应的消息来解释问题。argv[0]是程序名。第一个参数是argv[1] 另外,在尝试访问之前,请检查argc是否至少为两个。你也可以考虑 STD::StII, STD::ISTIGIS

我以前测试过这个程序,没有参数,只是简单地使用静态值,它运行得很好;所以我知道我上的课没什么问题


那么我在这里做错了什么呢?

argv[0]
是被调用的可执行文件的名称

您的第一个命令行参数将位于
argv[1]


为了确保您的程序不会再次以静默方式失败,您应该检查实际有多少个参数,以及
atof
是否返回值,并向用户显示相应的消息来解释问题。

argv[0]
是程序名。第一个参数是
argv[1]

另外,在尝试访问之前,请检查
argc
是否至少为两个。你也可以考虑<代码> STD::StII,<代码> STD::ISTIGISSWORDS或<代码> Sttood ,而不是<代码> ATOI 转换,因为它们可以检测伪输入。
最后,当一个自动变量足够时,为什么要使用
new
?你应该马上改掉这个习惯,或者用余生来调试内存泄漏。

请忽略那些教你如何使用
new
的东西。只需写
圈c(r),无
新建
,无
删除
,无指针。魔术哦,还有。我使用new关键字是因为我想在堆上而不是在堆栈上创建对象,这样更安全,因为它不存在堆栈溢出的风险(虽然单个对象不会做任何事情,但仍然)
\include“hidden_functions.h”//包含圆圈类
(继续讨论免费商店上手动内存管理的时髦性。是的,这很有道理)提示:您的堆栈溢出“解决方案”比您最初的“解决方案”也充满了更多的潜在危险。请接受SO社区的温和刺激,作为您正在学习好东西的迹象:/I我使用new在堆上创建对象,而不是在堆栈上;它是在上完成的purpose@ElectricCoffee: 当您确实需要动态分配(此处不需要)时,您应该始终使用,特别是智能指针,将对象绑定到作用域,并确保释放内存,即使引发异常。但您根本不需要动态对象,在不需要时使用堆是一个坏习惯。
radius: 0.0
diameter: 0.0
area: 0.0
circumference: 0.0