13

我需要将所有参数保存到向量或类似的东西。我不是程序员,所以我不知道该怎么做,但这就是我到目前为止所拥有的。我只想调用一个函数系统来传递所有参数。

#include "stdafx.h"
#include "iostream"
#include "vector"
#include <string>
using namespace std;

int main ( int argc, char *argv[] )
{
       for (int i=1; i<argc; i++)
       {
           if(strcmp(argv[i], "/all /renew") == 0)
           {
                 system("\"\"c:\\program files\\internet explorer\\iexplore.exe\" \"www.stackoverflow.com\"\"");
           }
           else
              system("c:\\windows\\system32\\ipconfig.exe"+**All Argv**);
       }

       return 0;
}
4

2 回答 2

64

我需要将所有参数保存到向量或其他东西

您可以使用向量的范围构造函数并传递适当的迭代器:

std::vector<std::string> arguments(argv + 1, argv + argc);

不是 100% 确定这是否是您所要求的。如果不是,请澄清。

于 2011-06-15T17:16:48.117 回答
0

要构建所有参数连接的字符串,然后根据这些参数运行命令,您可以使用类似的东西:

#include <string>
using namespace std;
string concatenate ( int argc, char* argv[] )
{
    if (argc < 1) {
        return "";
    }
    string result(argv[0]);
    for (int i=1; i < argc; ++i) {
        result += " ";
        result += argv[i];
    }
    return result;
}
int main ( int argc, char* argv[] )
{
    const string arguments = concatenate(argc-1, argv+1);
    if (arguments == "/all /renew") {
        const string program = "c:\\windows\\system32\\ipconfig.exe";
        const string command = program + " " + arguments;
        system(command.c_str());
    } else {
        system("\"\"c:\\program files\\internet explorer\\iexplore.exe\" \"www.stackoverflow.com\"\"");
    }
}
于 2011-06-15T17:29:57.217 回答