简体   繁体   中英

Split command line argument into arguments/a vector using C++

I have a C++ project that was previously receiving multiple command line arguments with code like so:

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

  for (int i = 1; i < 4; i = i + 1) {
    // do some stuff with argv[i]
    int in_arg = m[argv[i]];
  }

  return 0
}

Using this code, an example command line argument might be:

C:\MyFolder\MyExecutable.exe 4 0 1

However, due to plugging this code into a wider project my command line will now have to look like this instead:

C:\MyFolder\MyExecutable.exe 401

How can I split the argument 401 into a vector or similar that is functionally the same as having three input arguments like 4 0 1 so that my line:

int in_arg = argv[i];

...could be repointed to something like:

int in_arg = new_vector[i];

I only dabble with C++, so apologies if I am asking basic questions.

Thanks

If you already know that the 1st argument is the one to use it's simple, copy it to a string and then access it using one of the iteration options given by C++, I'm using a foreach type cycle:

#include <iostream>
#include <vector>

int main(int argc, char** argv)
{    
    if(argc < 2){
        std::cout << "Not enough arguments";  //<-- args check
        return 0;
    }
    std::string s1;
    s1 = argv[1]; //<-- copy argument to a string type to use string iterator
    std::vector<int> args_vector;

    for (char c : s1) {
        args_vector.push_back(c - '0'); // convert char to integer and save it in vector
    }

    for(int i: args_vector){ // print the args in integer format, 1 by 1
        std::cout << i << " ";
    }
    return 0;
}

You could create string s out of the arguments and just go though them character by character:

#include <iostream>
#include <string>
#include <vector>

int cppmain(std::string program, std::vector<std::string> args) {
    std::cout << program << " got " << args.size() << " argument(s):\n";

    for(auto& arg : args) {              // each argument as a string
        std::cout << " " << arg << '\n';

        for(char ch : arg) {             // each char in the current argument
            if(ch < 0) continue;         // skip negative char:s

            int in_arg = m[ch];          // assuming it was: int in_arg = m[*argv[i]];

            // use in_arg

        }
    }
    return 0;
}

int main(int argc, char* argv[]) {
    //
    //         string from char*
    //                |
    //                V
    return cppmain(argv[0], {argv + 1, argv + argc});
    //                      ^                     ^
    //                      |                     |
    //                     vector<string> from char*[]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM