Last active
August 7, 2022 19:57
-
-
Save plasticbox/3708a6cdfbece8cd224487f9ca9794cd to your computer and use it in GitHub Desktop.
Simple Parse Command Line Arguments in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| std::string getCmdOption(int argc, char* argv[], const std::string& option) | |
| { | |
| std::string cmd; | |
| for( int i = 0; i < argc; ++i) | |
| { | |
| std::string arg = argv[i]; | |
| if(0 == arg.find(option)) | |
| { | |
| std::size_t found = arg.find_first_of(option); | |
| cmd =arg.substr(found + 1); | |
| return cmd; | |
| } | |
| } | |
| return cmd; | |
| } | |
| // simple.exe -ip="127.0.0.1" -port=1000 | |
| std::string ip = getCmdOption(argc, argv, "-ip="); | |
| std::string port = getCmdOption(argc, argv, "-port="); |
Author
Author
Breaks when following parameter is passed.
// simple.exe -host=www.google.com -port=1000
Issue with "find_last_of". It matches any character of source. Here, character 'o' from "-host" is matched with 'o' from ".com".
So "m" is returned.
Updated code: Replace line number 9 with std::size_t found = arg.find_first_of("=");
thanks ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks ;)