通过main传递争论 - 检查是否有效输入

Pho*_*rce -2 c++ g++ argument-passing command-line-arguments

我试图通过main传递参数,这工作正常,然后检查传入的参数是否包含正确的格式/值.但是,即使我通过正确的格式,它仍然显示有错误,这里是代码:

int main(int argc, char* argv[]) {

/* Check if arguments are being passed through */ 

if(argc == 1){
    cout << endl << "--- ERROR ---" << endl;
    exit(0);
}

/* Check if the first argument contains the correct data */
string file_name = argv[1];

/* Handle operation */

string operation = argv[2];

if(operation != "-t" || operation != "-r")
{
    cout << "Something is not right";
}

}
Run Code Online (Sandbox Code Playgroud)

如果我这样做:cout << operation;那么结果将是:-t当我运行应用程序时传递-t.

谁能建议我哪里出错了?

更新:

我会传递这些论点:

./main something.wav -t

我期待if语句:

if(operation != "-t" || operation != "-r")
{
    cout << "Something is not right";
}
Run Code Online (Sandbox Code Playgroud)

要返回负数,因为我输入的值是-t

Dav*_*rtz 5

if(operation != "-t" || operation != "-r")
{
    cout << "Something is not right";
}
Run Code Online (Sandbox Code Playgroud)

无论操作是什么,它必须不等于"-t"或不等于"-r",所以这将始终打印"Something is right".

我期待if语句:
返回负数,因为我输入的值是-t

OR的后半部分是真的.如果前半部分或后半部分为真,则OR为真.你想要的((operation != "-t") && (operation != "-r")).这样,if只有输入不是-t 并且它也不是-r 时才会触发.