Integer Arguments for C ++

I have a C ++ calculator that should take arguments when executed. However, when I entered 7 as an argument, it could be 10354 when entering 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;
}
+5
source share
3 answers

Where would you not get it int argv[]? The second argument mainis char* argv[].

You can convert these command line arguments from string to integer using strtolor with floating point using strtod.

For instance:

    a=strtol(argv[1], nullptr, 0);
    b=strtol(argv[2], nullptr, 0);

But you cannot just change the parameter type, because the operating system will give you command line arguments in string form, whether you like it or not.

. #include <stdlib.h> ( #include <cstdlib> using std::strtol;) strtol.


, strtol atoi. , , . NUL, . , , , argc, , argv.

:

char* endp;
a = strtol(argv[1], &endp, 0);
if (endp == argv[1] || *endp) { /* failed, handle error */ }
+20

int main(int argc, char *argv[]). argv - .

7, ( "7" ). atoi(), 7.

+4

The second argument to main should either be char* argv[]or char** argv. Then you must convert them to int.

+2
source

All Articles