diff --git a/include/argparse/argparse.hpp b/include/argparse/argparse.hpp index 3e43804..fa31ef0 100644 --- a/include/argparse/argparse.hpp +++ b/include/argparse/argparse.hpp @@ -1361,14 +1361,15 @@ public: explicit ArgumentParser(std::string program_name = {}, std::string version = "1.0", default_arguments add_args = default_arguments::all, - bool exit_on_default_arguments = true) + bool exit_on_default_arguments = true, + std::ostream &os = std::cout) : m_program_name(std::move(program_name)), m_version(std::move(version)), m_exit_on_default_arguments(exit_on_default_arguments), m_parser_path(m_program_name) { if ((add_args & default_arguments::help) == default_arguments::help) { add_argument("-h", "--help") .action([&](const auto & /*unused*/) { - std::cout << help().str(); + os << help().str(); if (m_exit_on_default_arguments) { std::exit(0); } @@ -1381,7 +1382,7 @@ public: if ((add_args & default_arguments::version) == default_arguments::version) { add_argument("-v", "--version") .action([&](const auto & /*unused*/) { - std::cout << m_version << std::endl; + os << m_version << std::endl; if (m_exit_on_default_arguments) { std::exit(0); } @@ -1845,7 +1846,7 @@ private: if (m_positional_arguments.empty()) { // Ask the user if they argument they provided was a typo - // for some sub-parser, + // for some sub-parser, // e.g., user provided `git totes` instead of `git notes` if (!m_subparser_map.empty()) { throw std::runtime_error( diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index c7b5c13..718e14a 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -49,6 +49,7 @@ file(GLOB ARGPARSE_TEST_SOURCES test_repr.cpp test_required_arguments.cpp test_scan.cpp + test_stringstream.cpp test_value_semantics.cpp test_version.cpp test_subparsers.cpp diff --git a/test/test_error_reporting.cpp b/test/test_error_reporting.cpp index 648cb47..0c91132 100644 --- a/test/test_error_reporting.cpp +++ b/test/test_error_reporting.cpp @@ -35,7 +35,8 @@ TEST_CASE("Missing optional argument name" * test_suite("error_reporting")) { } } -TEST_CASE("Missing optional argument name (some flag arguments)" * test_suite("error_reporting")) { +TEST_CASE("Missing optional argument name (some flag arguments)" * + test_suite("error_reporting")) { argparse::ArgumentParser parser("test"); parser.add_argument("-a").flag(); parser.add_argument("-b").flag(); diff --git a/test/test_stringstream.cpp b/test/test_stringstream.cpp new file mode 100644 index 0000000..105bb40 --- /dev/null +++ b/test/test_stringstream.cpp @@ -0,0 +1,20 @@ +#ifdef WITH_MODULE +import argparse; +#else +#include +#endif +#include + +#include +#include +#include + +using doctest::test_suite; + +TEST_CASE("Get Version String" * test_suite("stringstream")) { + std::stringstream os; + argparse::ArgumentParser program("test", "1.0", + argparse::default_arguments::all, false, os); + program.parse_args({"test", "--version"}); + REQUIRE(os.str() == "1.0\n"); +} \ No newline at end of file