繁体   English   中英

将参数从命令行传递到C ++

[英]Passing parameters from command line to C++

在网上搜索如何将命令行参数传递给C ++代码的示例,我想到了一篇废弃的文章,其中对此过程进行了解释。 该代码无法正常工作,经过一些修改后,我想到了以下(有效)代码:

#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

返回下一个输出:

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

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

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

*argv[i+1]

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

要获得全部价值,请使用类似

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

代替。

您不能将字符串存储在单个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函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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