0

I am trying to figure a way to add an optional quiet switch to my command line arguments. The program I'm working on is a text to HTML converter, and at minimum requires a text sourcefile to be included in order for the program to run. What I am trying to get, is when a user enters -q anywhere in the argument list, the program will still run but suppress the output to the console. I have tried a few if statements and loops that will re assign argument values to my infile and outfile variables but those are not working either. The code can be found here: https://gist.github.com/anonymous/ab8ecfd09bddba0d4fcc. I am still relatively new to working with C++ so if you provide an explanation as to how to get closer to my goal in a simple way, I'd really appreciate it.

4

1 回答 1

0

-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] );
}

就像我说的,我没有测试任何东西,它只是向我跳了出来。

编辑

我将如何解析源文件、目标文件和 -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];
    }
}

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

于 2013-07-08T21:53:35.547 回答