4

I am studying C++ and I am focusing on cout manipulator functions.

By running the following code I get an indentation in the second line containing Gauthier.

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::setw(10) << std::setiosflags(std::ios::left)
        << "Mathieu\n"
        << "Gauthier\n"
        << "Paul\n"
        << "Louis\n"
        << "Pierre\n"
        << std::endl;
    return 0;
}

Can someone explain to me what is happening? Why Gauthier is indented while the other names are not?

Mathieu
  Gauthier
Paul
Louis
Pierre

Program ended with exit code: 0
Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
  • 1
    Does this answer your question? [Which iomanip manipulators are 'sticky'?](https://stackoverflow.com/questions/1532640/which-iomanip-manipulators-are-sticky) – underscore_d Jul 10 '20 at 14:11

1 Answers1

4

std::ios::left tells to add fill characters to the right, i.e. it adds few characters to first string, so "Mathieu\n" "becomes" "Mathieu\n ". There is new line character at the end ('\n'), so added spaces are moved to next line (Gauthier). So it's not indentation of second line, those are trailing characters from first.

Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
  • 1
    This is a surprising answer (and it doesn't sound that bad). However, I made this [**Test fiddling on coliru**](http://coliru.stacked-crooked.com/a/a0f6738a53b178ea) which I struggle to fit into your explanation. – Scheff's Cat Jul 10 '20 at 14:08
  • If this is true, why do spaces not get added to the other, even shorter, names? (Hint: we think `setw()` is the real key here) – underscore_d Jul 10 '20 at 14:10
  • `std::cout < – Umar Farooq Jul 10 '20 at 14:11
  • Even more funny: Resetting with `std::setw(0)` at begin of each output line doesn't change the result: [**Further test fiddling on coliru**](http://coliru.stacked-crooked.com/a/2f1dd4fb0f7506d5) – Scheff's Cat Jul 10 '20 at 14:11
  • @Scheff The answer explains your code. The only missing part of the answer is that `setw` is not sticky. – cigien Jul 10 '20 at 14:19
  • OK. Concerning the strange effects in my fiddling, I found the answer in [SO: Formatting the output stream, ios::left and ios::right](https://stackoverflow.com/a/9947528/7478597). Fixing this, I get [**Fixed test fiddling on coliru**](http://coliru.stacked-crooked.com/a/27ce882cd3f8b1d7), and, now, your explanation makes perfectly sense (to me). Though, the `std::resetiosflags(std::ios::adjustfield)` is something I find worth mentioned in your answer as well... ;-) – Scheff's Cat Jul 10 '20 at 14:19
  • 1
    @cygien Did you notice that the `std::ios::left` resulted in distinct effects in my first and second test? ;-) Though, I found the explanation for this as well. – Scheff's Cat Jul 10 '20 at 14:21