I have a sort of calculator in C++ that should accept arguments when executed. However, when I enter 7 as an argument, it might come out to be 10354 when put into a variable. Here is my code:
#include "stdafx.h"
#include <iostream>
int main(int argc, int argv[])
{
using namespace std;
int a;
int b;
if(argc==3){
a=argv[1];
b=argv[2];
}
else{
cout << "Please enter a number:";
cin >> a;
cout << "Please enter another number:";
cin >> b;
}
cout << "Addition:" << a+b << endl;
cout << "Subtaction:" << a-b << endl;
cout << "Multiplycation:" << a*b << endl;
cout << "Division:" << static_cast<long double>(a)/b << endl;
system("pause");
return 0;
}
Wherever did you get
int argv[]? The second argument tomainischar* argv[].You can convert these command line arguments from string to integer using
strtolor to floating-point usingstrtod.For example:
But you can’t just change the parameter type, because the operating system is going to give you your command-line arguments in string form whether you like it or not.
NOTE: You must
#include <stdlib.h>(or#include <cstdlib>andusing std::strtol;) to use thestrtolfunction.If you want error-checking, use
strtolinstead ofatoi. Using it is almost as easy, and it also gives you a pointer to the location in the string where parsing terminated. If that points to the terminating NUL, parsing was successful. And of course it is good that you verifyargcto make sure the user provided enough parameters, and avoid trying to read missing parameters fromargv.Example of error checking: