从命令行向 C++ 传递参数

Passing parameters from command line to C++

在网上搜索如何将命令行参数传递给 C++ 代码的示例,我想出了一个废弃的 post,其中解释了这个过程。这段代码不工作,经过一些修改我想出了以下(工作)代码:

#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>

using namespace std;

// When passing char arrays as parameters they must be pointers
int main(int argc, char* argv[]) {
    if (argc < 2) { // Check the value of argc. If not enough parameters have been passed, inform user and exit.
        std::cout << "Usage is -i <index file name including path and drive letter>\n"; // Inform the user of how to use the program
        std::cin.get();
        exit(0);
    } else { // if we got enough parameters...
        char* indFile;
        //std::cout << argv[0];
        for (int i = 1; i < argc; i++) { /* We will iterate over argv[] to get the parameters stored inside.
                                          * Note that we're starting on 1 because we don't need to know the 
                                          * path of the program, which is stored in argv[0] */
            if (i + 1 != argc) {// Check that we haven't finished parsing already
                if (strcmp(argv[i],"/x")==0) {
                    // We know the next argument *should* be the filename:
                    char indFile=*argv[i+1];
                    std::cout << "This is the value coming from std::cout << argv[i+1]: " << argv[i+1] <<"\n";
                    std::cout << "This is the value of indFile coming from char indFile=*argv[i+1]: " <<indFile  <<"\n";
                } else {
                    std::cout << argv[i]; 
                    std::cout << " Not enough or invalid arguments, please try again.\n";
                    Sleep(2000); 
                    exit(0);
                }   
            //std::cout << argv[i] << " ";
            }
        //... some more code
        std::cin.get();
        return 0;
        }   
    }
}

使用Windows命令行从

执行此代码:

MyProgram.exe /x filename

returns下一个输出:

This is the attribute of parameter /x: filename
This is the value from *argv[i+1]: f

原postfrom cplusplus.com没有编译;上面的代码确实如此。 如您所见,打印 argv[2] 给了我文件名。当我尝试将文件名捕获到另一个 var 以便我可以在 C++ 程序中使用它时,我只得到第一个字符(第二个响应行)。

现在回答我的问题:如何从指针指向的命令行参数中读取值? 希望有人能帮助这个 C++ 新手:-)

您不能将字符串存储在单个 char 中。

这是将 main 参数复制到更易于管理的对象的常用方法:

#include <string>
#include <vector>
using namespace std;

void foo( vector<string> const& args )
{
    // Whatever
    (void) args;
}

auto main( int n, char* raw_args[] )
    -> int
{
    vector<string> const args{ raw_args, raw_args + n };
    foo( args );
}

请注意,此代码依赖于一个假设,即用于 main 参数的编码可以代表实际的命令行参数。该假设在 Unix 领域成立,但在 Windows 中不成立。在 Windows 中,如果你想处理命令行参数中的非 ASCII 文本,你最好使用第三方解决方案或推出自己的解决方案,例如使用 Windows' GetCommandLine API 函数。

*argv[i+1]

访问 char* argv[] 参数的第一个字符。

要获得整个值,请使用类似

的东西
std::string filename(argv[i+1]);

相反。