Last active
August 29, 2015 14:06
-
-
Save jbernhard/ab5915dec580cc6eca5e to your computer and use it in GitHub Desktop.
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
#include<iostream> | |
#include<stdexcept> | |
#include<string> | |
void print_usage() { | |
std::cout << "usage: test [args...]\n" | |
<< '\n' | |
<< " help display this message and exit\n" | |
<< " x <int> set x\n"; | |
} | |
int main(int argc, char* argv[]) { | |
int x = 0; | |
for (int i = 1; i < argc; ++i) { | |
// possible uncaught exception | |
std::string key = std::string(argv[i]); | |
if ( key == "help" ) { | |
if (i == 1) { | |
print_usage(); | |
return 0; | |
} | |
} else if ( key == "x" ) { | |
++i; | |
// possible uncaught exception | |
std::string value = std::string(argv[i]); | |
try { | |
x = std::stoi(value); | |
} catch (const std::invalid_argument& e) { | |
std::cout << value << " is not a valid integer\n\n"; | |
print_usage(); | |
return 1; | |
} | |
} else { | |
std::cout << "invalid argument: " << key << "\n\n"; | |
print_usage(); | |
return 1; | |
} | |
} | |
std::cout << "x = " << x << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment