我如何正确地将整数的实际参数发送到main()以在C ++中计算总和?

问题描述 投票:0回答:1

这本书告诉我主要内容的声明如下:

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

int main(int argc, char** argv)

int argc, char** argv似乎是我唯一可以作为实际参数发送的东西。

现在我不想处理主字符串。

我想计算发送给main的整数的总和并返回总和。

#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;
}

以上是我最初的想法,但没有奏效。

由于从char到int的无效转换,因此无法编译

我认为参数必须是指向整数的指针的argc数组。

因此,以下是更新的代码:

#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;
}

用GCC编译代码后,输入./a.out 1 2 3,然后得到

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

我知道它远非完美,但比第一个要好。

我认为temp(或argv)降级为指向整数的指针。

因此**temp应为整数。

为什么**temp的打印看起来像指针?

我如何正确地将整数的实际参数发送给m​​ain以计算总和?

c++ parameters arguments parameter-passing main
1个回答
0
投票

您不能将整数发送到main。而是将发送到main的字符串转换为整数。您可以为此使用std::stoi功能

#include <iostream>
#include <string>

int main(int argc, int* argv[]) {
     std::cout << argc << std::endl; //print the number of the arguments passed
     int sum = 0;
     for (int i = 1; i < argc; ++i)
         sum += std::stoi(argv[i]);
     std::cout << "The sum of all integered entered is " << sum << std::endl;
     return 0;
}

在您的代码中**temp打印为整数,只有一个带有垃圾值。您的所有代码所做的就是假装您可以将整数发送给m​​ain,但不能这样做,因此您会得到垃圾输出。

© www.soinside.com 2019 - 2024. All rights reserved.