【问题标题】:C++ getting a "second command-line parameter"C++ 获得“第二个命令行参数”
【发布时间】:2018-07-26 08:34:48
【问题描述】:

我正在从事一项符合以下标准的作业:

任务:

“完美”数是等于其除数之和的整数 (其中 1 被视为除数)。例如,6 是完美的,因为它 除数是 1、2 和 3,而 1 + 2 + 3 是 6。同样,28 是完美的,因为 它等于 1 + 2 + 4 + 7 + 14。 一个“相当好”的数字是一个整数,它的“坏”—— 它的除数之和与数字本身之间的差异 - 不是 大于指定值。例如,如果最大坏度设置为 3、小于100的“相当不错”的数字有12个:2、3、4、6、8、10、16、18, 20、28、32 和 64; 你的任务是编写一个 C++ 程序,非常好,它决定了 小于指定值的指定最大不良数。极限值 执行程序时将最大坏度指定为命令行参数。

第一个问题是这样问的:

首先编写一个程序,打印完美数(坏度 0),直到小于 10000,由一个空格分隔。例如相当好 100 应该打印 6 28。

我在这里做了什么:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char** argv) 
{
   int candidate = 0;
   int badness;
    for(int i=2; i<10000; i++)
    { //Start for loop 1

        for (int j = 1; j<i; j++)
        { //Start for loop 2
            if (i % j == 0)
            {
                  candidate += j;

            }


        } //End for loop 2

        if(candidate %i ==0)
        { //Start of if 1
        cout << i << endl;
        } //End of if 1


            candidate = 0;


    } // End of loop 1
    return 0;
}

但是第二个问题问的是:

扩展程序,以便可以将不良限制指定为第二个命令行参数。例如相当好 100 3 将打印 2 3 4 6 8 10 16 18 20 28 32 64。

问题是,如何接收“第二个命令行参数”以在我的代码中使用?

注意:如果有帮助的话,我们需要在 Unix 终端 (cygwin) 上针对自动标记系统测试我们的代码。

希望这是足够的信息,对不起,如果不是这一切都非常混乱, 谢谢。

【问题讨论】:

  • gnu.org/software/libc/manual/html_node/Getopt.html 解析命令行选项和/或参数,或者您可以使用 std::cin 设置参数。
  • 您需要使用argcargv 参数。你的老师在给你作业之前没有告诉你这件事吗?
  • argc 包含char* 数组argv 内的参数数量。因此,如果argc&gt;2,您可以使用argv[2] 访问您的额外参数。 argv[0] 始终存在并代表程序名称(通常是可执行文件的路径)。
  • 这是很多细节只是为了询问命令行参数。 :)

标签: c++ unix


【解决方案1】:
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>

using namespace std;

int main(int argc, char** argv) 
{
    int n = 10000;
    int badnessLimit = 0;

    if (argc > 1) {
        istringstream nArg(argv[1]);
        if (!(nArg >> n) || !nArg.eof()) {
            cerr << "Invalid first argument\n";
            return 1;
        }
    }
    if (argc > 2) {
        istringstream badnessArg(argv[2]);
        if (!(badnessArg>> badnessLimit) || !badnessArg.eof()) {
            cerr << "Invalid second argument\n";
            return 2;
        }
    }
    cout << "           n = " << n << '\n';
    cout << "badnessLimit = " << badnessLimit << '\n';

    return 0;
}

https://wandbox.org/permlink/qGV2LdRnYxhU8Eh8

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2020-08-10
    • 2012-09-11
    • 2018-08-28
    相关资源
    最近更新 更多