[英]command line option
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
cout << argv[1] << endl;
if (argv[1]=="-r") cout << "success\n";
}
“成功”不会打印出来。 当我运行:$ ./hearts -r时,出现的唯一结果是:
-r
这让我感到困惑
我将继续告诉您,您不需要strcmp
。 C ++处理命令行参数的方法是尽快将它们转换为std::string
:
int main(int argc, const char* argv[])
{
// Make a vector of all command-line arguments
std::vector<std::string> args(argv, argv+argc);
// Now we can use std::string's operator==
if (args.size() > 1 && args[1] == "-r") {
std::cout << "Success" << std::endl;
}
return 0;
}
您可以将两个std::string
与==
运算符进行比较。 在args[1] == "-r"
的情况下, const char[]
字符串文字被转换为std::string
进行比较。 在您的代码中, argv[1]=="-r"
比较两个不相等的独立指针-它不比较C样式字符串的内容。
那是因为您在两个指针上使用==
。 它将检查指针是否相等,而不是指向相同数据的点。
要比较两个C字符串,请像下面这样使用strcmp
:
if (strcmp(argv[1], "-r") == 0)
您可能希望strcmp
比较两个字符串。 为了使==
为真,您的两个字符串必须引用相同的内存位置,因为"-r"
是一个编译时常量,所以这不可能发生。
您应该使用strcmp()
,它将按预期工作。 当使用==
您将比较指针,并且它们不能相同。
您应该尝试使用:
if (strcmp(argv[1],"-r")==0) cout << "success\n";
将参数与字符串文字进行比较。
在C语言中,字符串是字符数组(指向字符序列的指针)。 在您的代码中,相等运算符只比较两个绝对不同的指针值。 您应该使用strcmp
函数,或使用string
类:
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <cstring> // <-- here
using namespace std;
int main(int argc, char* argv[])
{
cout << argv[1] << endl;
if (strcmp(argv[1], "-r") == 0) // <-- and here
cout << "success\n";
}
要么
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <string> // <-- here
using namespace std;
int main(int argc, char* argv[])
{
cout << argv[1] << endl;
if (string(argv[1]) == "-r") // <-- and here
cout << "success\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.