Calculating two numbers from command line c++
This is my code :
#include <iostream>
using namespace std;
int main (int argc, char* argv[])
{
int frstNumb = atoi (argv[1]);
int scndNumb = atoi (argv[2]);
int sum = 0;
sum = frstNumb + scndNumb;
}
Okay, now its working for integers. What do I must do so I can put e.g. "2.5 and 1.2" in my par开发者_如何学JAVAameters? This program won't calculate that kind of numbers. Help?
Thanks
The arguments are always passed as strings. First of all, change the main function declaration to
int main (int argc, char* argv[])
Note that the return value of main MUST be int, otherwise it is nonstandard.
Second convert argv[1]
and argv[2]
to integers with either atoi
, which, to my taste, is a bit C-ish, although the simplest, or by boost::lexical_cast
e.g.
int i1 = atoi(argv[1]); //#include <cstdlib>
int i1 = boost::lexical_cast<int>(argv[1]); //#include <boost/lexical_cast.hpp>
Yep-- you want atoi()
.
int frstNumb = atoi(argv[1]);
int scndNumb = atoi(argv[2]);
I'd suggest googling atoi()
to see how it works, it will probably help you in the future.
argv[1]
and argv[2]
are strings. When you do the sum, wrap them with atoi()
calls so they are parsed and converted to integers.
Thanks to Mark Loeser and walkingTarget
Your declaration of main()
should be:
int main(int argc, char **argv)
or
int main(int argc, char *argv[])
main()
should always return an int
, and argv
should always be an array of strings.
As suggested in other answers, you first need to change declaration of function main
- argc
represents total number of arguments passed to it and argv
is an array of arguments themselves (each argument is an element in array; first element - argv[0]
- is path to this executing binary! argv[1]
is actually first argument from a command line).
Both in C and C++ you can use atoi
or sscanf
functions but in C++ you should take advantage of STL stringstream
's conversion capabilities:
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char* argv[])
{
if(argc != 3)
{
cerr << "Invalid number of operands" << endl;
return 1;
}
int n1 = 0;
int n2 = 0;
stringstream ss;
ss << argv[1];
ss >> n1;
ss.clear();
ss << argv[2];
ss >> n2;
int sum = n1 + n2;
return 0;
}
精彩评论