Save argv to vector or string

懵懂的女人 提交于 2019-11-29 19:24:45

问题


I need to save all arguments to a vector or something like this. I'm not a programmer, so I don't know how to do it, but here's what I've got so far. I just want to call a function system to pass all arguments after.

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

回答1:


i need to save all arguments to a vector or something

You can use the range constructor of the vector and pass appropriate iterators:

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

Not 100% sure if that's what you were asking. If not, clarify.




回答2:


To build string with all argument concatenated and then run a command based on those arguments, you can use something like:

#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\"\"");
    }
}


来源:https://stackoverflow.com/questions/6361606/save-argv-to-vector-or-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!