Convert command line argument to string

后端 未结 7 1169
囚心锁ツ
囚心锁ツ 2021-01-31 08:43

I have a program that reads hard-coded file-path and I want to make it read file-path from command line instead. For that purpose I changed the code like this:

#         


        
相关标签:
7条回答
  • 2021-01-31 08:58

    Because all attempts to print the argument I placed in my variable failed, here my 2 bytes for this question:

    std::string dump_name;
    
    (stuff..)
    
    if(argc>2)
    {
        dump_name.assign(argv[2]);
        fprintf(stdout, "ARGUMENT %s", dump_name.c_str());
    }
    

    Note the use of assign, and also the need for the c_str() function call.

    0 讨论(0)
  • 2021-01-31 08:59

    It's already an array of C-style strings:

    #include <iostream>
    #include <string>
    #include <vector>
    
    
    int main(int argc, char *argv[]) // Don't forget first integral argument 'argc'
    {
      std::string current_exec_name = argv[0]; // Name of the current exec program
      std::vector<std::string> all_args;
    
      if (argc > 1) {
        all_args.assign(argv + 1, argv + argc);
      }
    }
    

    Argument argc is count of arguments plus the current exec file.

    0 讨论(0)
  • 2021-01-31 09:10
    #include <iostream>
    
    std::string commandLineStr= "";
    for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));
    
    0 讨论(0)
  • 2021-01-31 09:13

    No need to upvote this. It would have been cool if Benjamin Lindley made his one-liner comment an answer, but since he hasn't, here goes:

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

    If you don't want to include argv[0] so you don't need to deal with the executable's location, just increment the pointer by one:

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

    0 讨论(0)
  • 2021-01-31 09:14

    It's simple. Just do this:

    #include <iostream>
    #include <vector>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
        std::vector<std::string> argList;
        for(int i=0;i<argc;i++)
            argList.push_back(argv[i]);
        //now you can access argList[n]
    }
    

    @Benjamin Lindley You are right. This is not a good solution. Please read the one answered by juanchopanza.

    0 讨论(0)
  • You can create an std::string

    #include <string>
    #include <vector>
    int main(int argc, char *argv[])
    {
      // check if there is more than one argument and use the second one
      //  (the first argument is the executable)
      if (argc > 1)
      {
        std::string arg1(argv[1]);
        // do stuff with arg1
      }
    
      // Or, copy all arguments into a container of strings
      std::vector<std::string> allArgs(argv, argv + argc);
    }
    
    0 讨论(0)
提交回复
热议问题