I wrote a simple program to calculate the hypotenuse length of a triangle. My question is, how can I give variables "side1" and "side2" values while executing the main function from the terminal? Code below:
#include <iostream>
#include <cmath>
int main(int side1, int side2) {
int c2 = (pow(side1, 2)) (pow(side2, 2));
std::cout << sqrt(c2) << std::endl;
return 0;
}
The function compiles without error, so normally I would execute the function from terminal using "./main.exe", but is there a way to pass values to variables side1 & side2 while executing? (ex: ./main.exe "5" "5"). I don't want to go the std::cin route because I already know how to do that. For the same reason, I don't want to assign values to the variables within the function (ex: int side1 {5};).
I don't know if this is possible to do or not, but sites like Leetcode have their functions set up this way, and I have no clue how they input values for test cases.
CodePudding user response:
The signature of the main function can be
int main(int argc, char *argv[])
so you get an argument count and a "string" array. Note that argv[0]
is the executable name, so side1
would be argv[1]
and side2
is argv[2]
.
CodePudding user response:
You need to get the command line argument strings and convert them to integers. Alas, this does increase the complexity of your program a little if you want to catch errors.
#include <cmath>
#include <iostream>
#include <string>
int help()
{
std::cerr <<
"usage:\n"
" a.exe SIDE1 SIDE2\n\n"
"Where SIDE1 and SIDE2 are integers.\n";
return 1;
}
int main( int argc, char ** argv )
{
int side1, side2;
if (argc != 3) return help();
try {
side1 = std::stoi( argv[1] );
side2 = std::stoi( argv[2] );
}
catch (...)
{
return help();
}
int c2 = side1*side1 side2*side2;
std::cout << std::sqrt( c2 ) << "\n";
}
You could leave a lot of that error checking out and just let the program crash without explanation, but IMHO it is always worth adding a usage clause to your program to help users (including yourself two months from now) figure out how to run the program.
CodePudding user response:
As noted previously, your function signature for main
is incorrect. The correct signature when you want to access command line arguments is:
int main(int argc, char **argv)
argc
is the count of arguments, the first being the name of the executable. argv
is an array of those arguments. We can:
- Check that the right number of arguments have been passed in, and print an error if not.
- Use
std::atoi
to convert those inputs into ints, at which point we can use them as we please.
#include <iostream>
#include <cstdlib>
int main(int argc, char **argv) {
if (argc != 3) {
std::cerr << "Usage: "<< argv[0]
<< " val1 val2" << std::endl;
return 1;
}
auto v1 = std::atoi(argv[1]);
auto v2 = std::atoi(argv[2]);
std::cout << v1 << ", " << v2 << std::endl;
return 0;
}
CodePudding user response:
Your main
signature is wrong. See https://en.cppreference.com/w/cpp/language/main_function.