Consider the following code:
std::string n("123456");
std::stringstream ss;
ss << std::setw(3) << n;
std::cout << ss.str() << " | " << (ss.fail() ? "True" : "False") << std::endl;
Why does this print out
123456 | False
instead of
123 | False
The effects of the width modifier are handled differently by different formatters. In the expression ss << std::setw(3) << n
, where n
has type std:string
, you're using operator<<(ostream&, const std::string&)
, which does the following (from cppreference):
a) If str.size() is not less than os.width(), uses the range [str.begin(), str.end()) as-is
In your case, str.size()
is 6
and ss.width()
is 3
, so the entire string is output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With