Reputation: 1
I would like to take a command line argument (which will be an integer greater than zero) and use it as an integer parameter in a function (to decide which part of the function to use).
double func(double x, double y, double z, int n) {
if (n==1) { return 1; }
if (n==2) { return 2; }
// etc
}
int main (int argc, char *argv[]) {
int n = argv[1];
// etc, later I call func(x,y,z,n) with this definition of n
}
When I try to compile, I get some warnings:
warning: invalid conversion from ‘char*’ to ‘int’
warning: initializing argument 4 of ‘double func(double, double, double, int)’
I think I understand why it's happening, I just don't know how to fix it. Nothing I've found so far googling has been too helpful. I'm quite new at C++, and any information that'd point me in the right direction would be great. Thank you for your time.
Upvotes: 0
Views: 2027
Reputation: 153792
You can use std::istringstream
to convert the number:
int main(int ac, char * av[]) {
int av1;
if (2 <= ac
&& std::istringstream(av[1]) >> av1) {
do_something_with(av1);
}
else {
report_error();
}
}
Upvotes: 1