Last active
December 13, 2023 23:16
-
-
Save mshafae/ed20598a5ccf74be58e34a18e3379ff0 to your computer and use it in GitHub Desktop.
Command line arguments in C++17 using a vector.
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
// Gist https://gist.github.com/ed20598a5ccf74be58e34a18e3379ff0 | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
int main(int argc, char const* argv[]) { | |
std::vector<std::string> command_line_arguments{argv, argv + argc}; | |
std::cout << "There are " << argc << " arguments on the command line.\n"; | |
int index{0}; | |
for (auto const& arg : command_line_arguments) { | |
std::cout << "arg #" << index << ": \"" << arg << "\"\n"; | |
index = index + 1; | |
} | |
if (command_line_arguments.size() > 3) { | |
int two_from_the_back = static_cast<int>(command_line_arguments.size()) - 2; | |
try { | |
std::cout << "\nThe argument at location " << 0 << " is \"" | |
<< command_line_arguments.at(0) << "\".\n"; | |
std::cout << "The argument at location " << two_from_the_back << " is \"" | |
<< command_line_arguments.at(two_from_the_back) << "\".\n"; | |
std::cout << "The argument at location " << command_line_arguments.size() - 1 | |
<< " is \"" | |
<< command_line_arguments.at(command_line_arguments.size() - 1) | |
<< "\".\n"; | |
} catch (std::exception const& e) { | |
std::cout << "There was a problem retrieving the argument.\n"; | |
return 1; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment