Ale*_*vic -1 c++ command-line-arguments
I am building a CLI app that should do something similar to this:
./app
Welcome to the app, Type -h or --help to learn more.
./app -h
list of commands:...
Run Code Online (Sandbox Code Playgroud)
Here is the code i am trying to build:
#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;
}
Run Code Online (Sandbox Code Playgroud)
But when i try to compile gcc gives following erros:
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") {
^~~~~~~~
Run Code Online (Sandbox Code Playgroud)
从C ++ 17开始,编写此代码的最佳方法如下:
#include <iostream>
#include <string_view>
int main(int argc, char** argv) {
using namespace std::literals;
std::cout << "Welcome to the app. Type -h or --help to learn more\n";
if (argv[0] == "-h"sv || argv[0] == "--help"sv) {
std::cout << "List of commands:...";
}
}
Run Code Online (Sandbox Code Playgroud)
在string_view标头存在之前,您可以使用""s std::string文字,它会产生与上面相同的代码,只包括string标准标头并更改"…"sv为"…"s。不幸的是,这样的代码会导致多余的分配,但是在这个特定示例中这是不相关的。