Proper way to print - think C++ 23+
I'm curious -
What is the proper way to print in a modern C++ program. Don't think about how you've aways printed with the simply using cout like this:
Code:
#include <iostream>
int main() {
std::string message = "The number is";
int number = 42;
std::cout << message << ": " << number << std::endl;
return 0;
}
Rather think C++ 23. Where things like format have been added:
Code:
#include <iostream>#include <format>
int main() {
std::string message = "The number is";
int number = 42;
std::cout << std::format("{}: {}\n", message, number);
return 0; }
Or would you now do it using std::print?
Code:
#include <print>
int main() {
int number = 42;
std::string message = "The number is";
std::print("{}: {}\n", message, number);
return 0; }
Or is std::print not yet fully accepted, and thus the best way is to use format?
Again, I don't care as much about what people are doing, but rather about what people SHOULD Be doing if they are following current, modern standards.
Thoughts?
Re: Proper way to print - think C++ 23+
Should is std:: print - if available. If not then std::format_to
std::format_to(std:: ostream_iterator<char>(std::cout), "{}: {}\n", message, number);
This removes the need for a temp std::string.
Note that the iterator can be set once:
Code:
const auto fmt_to { std:: ostream_iterator<char>(std::cout) };
std::format_to(fmt_to, "{}: {}\n", message, number);