Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior of std::setw when used with std::stringstream

Tags:

c++

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
like image 572
Benjamin Westrich Avatar asked Sep 05 '25 15:09

Benjamin Westrich


1 Answers

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

like image 124
Cubbi Avatar answered Sep 08 '25 22:09

Cubbi