argv
is an array of pointers to raw strings, you can't obtain a range from it directly.
With C++17 you can use std::string_view
to avoid allocating strings:
for (auto && str : std::vector<std::string_view> { argv, argv + argc })
{
std::printf("%s\n", str.data()); // Be careful!
std::cout << str << std::endl; // Always fine
fmt::print("{}\n", str); // <3
}
Take caution when using string_view
with printf
because:
Unlike std::basic_string::data()
and string literals, data()
may return a pointer to a buffer that is not null-terminated.
argv
always contains null-terminated strings so you're fine here though.
Without C++17 you can simply use std::string
:
for (auto && str : std::vector<std::string> { argv, argv + argc })
std::printf("param: %s\n", str.c_str());
Starting from C++20 you can use std::span
:
for (auto && str : std::span(argv, argc))
std::printf("param: %s\n", str);