【问题标题】:Passing arguements through main - Checking to see if a valid input通过 main 传递参数 - 检查是否有效输入
【发布时间】:2013-03-06 20:30:41
【问题描述】:

我正在尝试通过 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 &lt;&lt; operation;,那么结果将是:-t 在我运行应用程序时传递 -t 时。

谁能建议我哪里出错了?

更新:

我将传递这些参数:

./main something.wav -t

我期待 if 语句:

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

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

【问题讨论】:

  • 嗯?你传递了什么参数,你期望什么输出,你得到什么?
  • 你的测试是错误的:if(operation != "-t" || operation != "-r") - 它应该是:if(operation != "-t" &amp;&amp; operation != "-r")
  • @PaulR 谢谢。你能把它作为答案,我会接受:)
  • @downvoter - 你能告诉我为什么我的帖子被否决了吗?给出一个简短的答案并告诉我为什么,而不是仅仅投反对票..
  • @Phorce:我没有投反对票,但人们确实倾向于投反对票“即使没有我告诉你我期望它做什么以及它做了什么”,也可以在我的代码中找到微不足道的错误”类型的问题。

标签: c++ g++ command-line-arguments argument-passing


【解决方案1】:
if(operation != "-t" || operation != "-r")
{
    cout << "Something is not right";
}

无论操作是什么,它必须要么不等于“-t”,要么不等于“-r”,所以这将总是打印“Something is not right”。

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

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

【讨论】:

    猜你喜欢
    • 2013-10-22
    • 2014-07-09
    • 2014-04-13
    • 2014-12-28
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多