Question

I have a simple test program in C++ that prints out attributes of a circle

#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;
}

when I run my program with the parameter 2.4 it outputs:

radius: 0.0
diameter: 0.0
area: 0.0
circumference: 0.0

I've previously tested the program without the parameter, but simply using static values, and it ran just fine; so I know there's nothing wrong with the class I made...

So what did I do wrong here?

Was it helpful?

Solution

argv[0] is the program name. You want argv[1] for the first argument.

Also, check that argc is at least two before trying to access it. You might also consider std::stoi, std::istringstream or strtod rather than atoi for conversion, since they can detect bogus input.

Finally, why are using new when an automatic variable will suffice? You should get out of that habit straight away, or spend the rest of eternity debugging memory leaks.

OTHER TIPS

argv[0] is the name of the executable being invoked.

Your first command line parameter will be in argv[1].

To make sure that your program does not silently fail again, you should check how many parameters you actually have and if the atof returns a value, and show a message to the user explaining the issue accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top