开发者

integer arguments for c++

I have a sort of calculator in C++ that should accept arguments when ex开发者_运维问答ecuted. 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 to main is char* argv[].

You can convert these command line arguments from string to integer using strtol or to floating-point using strtod.

For example:

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

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> and using std::strtol;) to use the strtol function.


If you want error-checking, use strtol instead of atoi. 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 verify argc to make sure the user provided enough parameters, and avoid trying to read missing parameters from argv.

Example of error checking:

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


The function signature is int main(int argc, char *argv[]). argv is an array of string pointers.

If the argument is 7, it will be in the form of a string ("7"). Use atoi() to convert it to the number 7.


Second argument in the main should either either be char* argv[] or char** argv. Then you have to have convert them to int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜