integer arguments for c++ -


i have sort of calculator in c++ should accept arguments when executed. however, when enter 7 argument, might come out 10354 when put variable. here 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 number:";         cin >> a;         cout << "please enter 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 int argv[]? second argument main char* argv[].

you can convert these command line arguments string integer using atoi or strtod.

for example:

    a=atoi(argv[1]);     b=atoi(argv[2]); 

but can't change parameter type, because operating system going give command-line arguments in string form whether or not.

note: must #include <stdlib.h> (or #include <cstdlib> , using std::atoi;) use atoi function.


if want error-checking, use strtol instead of atoi. using easy, , gives pointer location in string parsing terminated. if points terminating nul, parsing successful. , of course verify argc make sure user provided enough parameters, , avoid trying read missing parameters argv.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -