Question

I was trying to affirm my knowledge about how streams work with doubles and various manipulators, and stumbled upon G++ doing something strange:

int main() {
    double v = 10.0/3.;
    //std::cout << v << '\n';
    std::cout << std::setw(5) << std::setprecision(2) << v << '\n';
    std::cout << std::setw(5) << std::setprecision(2) << std::fixed << v << '\n';
}

Output:

3.3      //why is this left aligned?
 3.33    //why is this right aligned? which is right?

See it live here

Then I uncommented that first cout and got different results!

3.33333 //which alignment is this?
  3.3   //now this is right aligned?!
 3.33   //that implies right-aligned is correct

Subsequent tests show that the first double I stream out is left aligned, and all subsequent doubles are right aligned:

double v = 10.0/3.;
std::cout << std::setw(10) << v << '\n';
std::cout << std::setw(5) << std::setprecision(2) << std::fixed << v << '\n';
std::cout << std::setw(5) << std::setprecision(2) << v << '\n';
std::cout << std::setw(5) << std::setprecision(2) << v << '\n';

Output:

3.33333           //well, this is left aligned
 3.33
  3.3           
  3.3             //all subsequent tests are right aligned

Clang++ on Coliru is doing the same thing, I presume because they're using the same library.

I know the answer to "is this a G++ bug" is no 99.9% of the time, so can someone potentially explain the behavior I'm seeing?

Was it helpful?

Solution

After running this on other IDEs I would conclude that this is a problem not with g++/clang++, nor is any standard behavior, but a problem with the Coliru editor itself. I ran this on several different sites including Rextester and Ideone and I got the correct output for all of them. This seems to be a problem only belonging to the Coliru editor.

Streams are, by default, right-justified. When setting the width using std::setw(), the stream will insert padding characters as specified by out.fill() into the beginning (or end) of the output stream. I've noticed that Coliru doesn't add any padding characters on the first output operation when the stream is using the default fill character (a simple space). But when I change the fill character to anything other than a space, it works just fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top