将-q开关添加到参数列表中

Adding a -q switch to a list of arguments

本文关键字:参数 列表 添加 开关      更新时间:2023-10-16

我正试图找到一种方法,在我的命令行参数中添加一个可选的安静开关。我正在开发的程序是一个文本到HTML的转换器,至少需要包含一个文本源文件才能运行程序。我想得到的是,当用户在参数列表中的任何位置输入-q时,程序仍然会运行,但会抑制控制台的输出。我已经尝试了一些if语句和循环,它们将为我的内野变量和外野变量重新分配参数值,但它们也不起作用。代码可在此处找到:https://gist.github.com/anonymous/ab8ecfd09bddba0d4fcc.我对使用C++还比较陌生,所以如果你能以简单的方式解释如何更接近我的目标,我会非常感激。

有东西马上向我扑来,你正在测试的参数是否等于-q

if( strcmp( argv[1], "-q" ) != 0) //This is an example of what I am trying to do.
{
    quiet = true;
    infile.open( argv[2] );
}

这是不正确的。strcmp返回比较的两个字符串之间的词法差异:http://www.cplusplus.com/reference/cstring/strcmp/

所以我相信你想要

if( strcmp( argv[1], "-q" ) == 0) //This is an example of what I am trying to do.
{
    quiet = true;
    infile.open( argv[2] );
}

就像我说的,我没有测试任何东西,它只是突然向我袭来。

编辑

如何在sourcefile、destfile和-q选项中进行解析

std::string sourceFile;
std::string destFile;
if ( argc == 3 )
{
    sourceFile = std::string( argv[1] );
    destFile = std::string( argv[2] );
}
else if ( argc == 4 )
{
    // quiet mode is enabled
    std::string arg1( argv[1] );
    std::string arg2( argv[2] );
    std::string arg3( argv[3] );
    if ( arg1 != "-q" )
        vec.push_back( std::string( arg1 );
    if ( arg2 != "-q" )
        vec.push_back( std::string( arg2 );
    if ( arg3 != "-q" )
        vec.push_back( std::string( arg3 );
    if ( vec.size() != 2 )
    {
        // maybe error? 
    }
    else
    {
        sourceFile = vec[0];
        destFile = vec[1];
    }
}

当然没有尽可能干净,而且我还没有测试过,所以可能会有一个小错误。