Hey everyone, I am trying to use command line arguments. The program should take 5 integers via the command prompt and then add all the numbers and print the sum. It is not working. I got a previous version to compile and run, but It was not correct. It essentially ran the program from the command propmt, instead of taking the arguments autmatically
#include <iostream>
#include <limits>
usingnamespace std;
int main(int argc, char *argv[])
{
//if the user did not enter enough arguments
if(argc < 2)
{
//type out what is required
cerr << "Usage: " << argv[0] << " integers" << endl;
return 1;
}
int input[5]; //array declaration
for(int i = 0; i < argc; ++i)
{
cout << i + 1 << "). ";
//input validation
if((double)argv[i] != (int)arv[i])
{
cerr << "ERROR: Arguments not valid\n";
return 1;
}
input[i] = argv[i]; //initializes each array index
}
int sum = 0; //sum of the values entered
//sums the integers entered
for(int i = 0; i < 5; ++i)
sum += input[i];
cout << "Sum of all integers entered = " << sum << endl;
return 0;
}
Use the atoi function to get integers and atof to get floating point numbers from argv. See an example here: http://www.cs.ucsb.edu/~pconrad/cs16/topics/cmdlineargs/
Casting an array of chars to int or to double is not supported in c++.
//if the user did not enter enough arguments
if(argc < 2)
{
//type out what is required
cerr << "Usage: " << argv[0] << " integers" << endl;
return 1;
}
Besides your Usage: output being wrong, if it requires 5 integers and the user input 4 the error would not be displayed with if(argc < 2). They only need to enter two integers to pass that test. Usage: only asks for one integer.
In summary:
Teaching atoi to beginners is just easier. There will be no chance of them being confused by extra parameters. I say this even though I use strtol for better error checking in my production code.
Edit: I changed the code to also show detection of whether or not the number is an integer.
#include <iostream>
#include <cstdlib>
#include <limits>
usingnamespace std;
int main(int argc, char *argv[])
{
//if the user did not enter enough arguments
if(argc != 6)
{
//type out what is required
cerr << "Usage: " << argv[0] << " int1 int2 int3 int4 int5\n";
return 1;
}
int input[5]; //array declaration
for(int i = 1; i < argc; ++i)
{
input[i-1] = atoi(argv[i]); //converts input to int
}
int sum = 0; //sum of the values entered
//sums the integers entered
for(int i = 0; i < 5; ++i)
sum += input[i];
cout << "Sum of all integers entered = " << sum << endl;
return 0;
}