【发布时间】: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 << 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" && operation != "-r") -
@PaulR 谢谢。你能把它作为答案,我会接受:)
-
@downvoter - 你能告诉我为什么我的帖子被否决了吗?给出一个简短的答案并告诉我为什么,而不是仅仅投反对票..
-
@Phorce:我没有投反对票,但人们确实倾向于投反对票“即使没有我告诉你我期望它做什么以及它做了什么”,也可以在我的代码中找到微不足道的错误”类型的问题。
标签: c++ g++ command-line-arguments argument-passing