Skip to content

Instantly share code, notes, and snippets.

@plasticbox
Last active August 7, 2022 19:57
Show Gist options
  • Save plasticbox/3708a6cdfbece8cd224487f9ca9794cd to your computer and use it in GitHub Desktop.
Save plasticbox/3708a6cdfbece8cd224487f9ca9794cd to your computer and use it in GitHub Desktop.
Simple Parse Command Line Arguments in C++
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=");
@TeddybearCrisis
Copy link

thanks - I like it.

and for the sake of understanding I think this would improve the example (line 19):
... getCmdOption(argc, argv, "-port=");

@sgupta38
Copy link

sgupta38 commented Feb 26, 2021

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("=");

@plasticbox
Copy link
Author

thanks - I like it.

and for the sake of understanding I think this would improve the example (line 19):
... getCmdOption(argc, argv, "-port=");

thanks ;)

@plasticbox
Copy link
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