Search code examples
c++parametersargumentsparameter-passingprogram-entry-point

How can I correctly send actual parameters of integers to main() to calculate the sum in C++?


The book tells me The declaration of the main looks like this:

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

or

int main(int argc, char** argv)

It seems that int argc, char** argv are the only things I can send as actual parameters.

Now I don't want to deal with strings main.

I want to calculate the sum of integers sent to main and return the sum.

#include <iostream>
int main(int n, char** argv) {
        std::cout << n << std::endl;
        char** temp = argv;
        int sum = 0;
        int i = 0;
        while (*temp != NULL) {
                std::cout << i++ << ':' << *temp << std::endl;
                sum += *temp++;
        }

        return 0;
}

The above is my original thinking that fails to work.

It can't be compiled due to Invalid conversion from char to int

I think argument must be array of argc of pointer to integer.

So following is the updated code:

#include <iostream>

int main(int n, int* argv[]) {
        std::cout << n << std::endl; //print the number of the arguments passed
        int** temp = argv;
        int sum = 0;
        int i = 0;

        while (*temp != NULL) {
                std::cout << i++ << ':' << **temp << std::endl;
                if (*temp != argv[0])
                        sum += **temp;
                ++temp;
        }
        std::cout << "The sum of all integered entered is " << sum << std::endl;

        return 0;
}

After compiling the code with GCC, I enter ./a.out 1 2 3, and I get

4
0:778121006
1:3276849
2:3342386
3:1213399091
The sum of all integered entered is 1220018326

I know it is far from perfect but it is better than the first one.

I think temp(or argv) is degraded to pointer to a pointer to an integer.

So **temp should be an integer.

Why the print of **temp looks like a pointer?

How can I correctly send actual parameters of integers to main to calculate the sum?


Solution

  • You can't change the signature of the main function, it will remain the same anyway. The right signature is :

    int main(char ac, char **av); // or char *av[] if you prefer
    

    ac : argument count av : argument values

    You get only strings as parameter, a chain of characters ended by null byte '\0'. Also, the first value in av is always the program name itself. Try to print it ;)

    Using a simple function you can convert this to a number, there is one for int, float, double, long, unsigned long and unsigned long long.

    • std::stoi
    • std::stof
    • std::stod
    • std::stol
    • std::stoul
    • std::stoull

    All of them takes a string as parameter and return the parsed number.

    for (int i = 1 ; i < ac ; i++) { // we don't want the first value, so we start from 1
       int number = std::stoi(av[i]);
       std::cout << number << std::endl;
    }