【发布时间】:2019-04-03 17:01:14
【问题描述】:
我正在构建一个 CLI 应用程序,它应该执行与此类似的操作:
./app
Welcome to the app, Type -h or --help to learn more.
./app -h
list of commands:...
这是我正在尝试构建的代码:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
cout << "Welcome to the app. Type -h or --help to learn more\n";
if(argv == "-h" || argv == "--help") {
cout << "List of commands:...";
}
return 0;
}
但是当我尝试编译 gcc 时会出现以下错误:
error: comparison between distinct pointer types ‘char**’ and ‘const char*’ lacks a cast [-fpermissive]
if(argv == "-h" || argv == "--help") {
^~~~
error: comparison between distinct pointer types ‘char**’ and ‘const char*’ lacks a cast [-fpermissive]
if(argv == "-h" || argv == "--help") {
^~~~~~~~
【问题讨论】:
-
用例如
argv == "-h"你比较两个永远不会相等的 指针。如错误消息中所述,指针也具有不同的类型。我建议你 get a couple of good books 阅读,因为他们应该有关于你想要什么的信息。如果您稍微搜索一下,还有很多关于如何做到这一点的教程和示例。 -
看看
getopt()。 -
假设
-h是第一个命令行参数-并且您已经检查argc以确保提供了这样的参数-您需要执行strcmp(argv[1], "-h")。更好的是,不要使用 C 字符串比较函数,而是弄清楚如何使用 C++std::string。
标签: c++ command-line-arguments