通过main传递参数-检查输入是否有效

Passing arguements through main - Checking to see if a valid input

本文关键字:检查 输入 是否 有效 参数 main 通过      更新时间:2023-10-16

我试图通过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";
}
}

如果我执行:cout << operation;,那么当我运行应用程序时,通过-t传递结果将是:-t

谁能建议我哪里可能出错?

更新:

我将传入这些参数:

./main something.wav -t

我正在等待if语句:

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

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

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

无论操作是什么,它必须要么不等于"-t"要么不等于"-r",因此将总是打印"Something is not right"。

我期待if语句:
因为我输入的值是-t

,所以返回负值

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