Search code examples
c++setw

How does the setw stream manipulator work?


How does the setw stream manipulator (space count) work? When there is one \t, for example, I want to print a with four spaces, so I use \t and I compare \t with setw.

The code that I wrote:

# include <iostream>
# include <iomanip>

int main()
{
    std::cout<<"\t"<<"a\n";
    std::cout<<std::setw(9)<<"a\n";
    return 0;
}

Output:

   a // This is 1 '\t'
   a // This is setw()

So what I thought was:

setw(18) = \t\t

The code worked. But when I deleted the \n, it did not become one straight line.

# include <iostream>
# include <iomanip>

int main()
{
    std::cout<<"\t\t"<<"a\n";
    std::cout<<std::setw(18)<<"a";
    return 0;
}

It gives me this output:

      a
       a

What's wrong?


Solution

  • That's because you need to add a \n at the setw(18). And this applies to any setw.

    Sample code:

    # include <iostream>
    # include <iomanip>
    int main()
    {
    std::cout<<"\t\t"<<"a\n";
    std::cout<<std::setw(18)<<"a\n"; // And you add the \n here
    return 0;
    }
    

    Output:

            a
            a
    

    And another solution is:

    # include <iostream>
    # include <iomanip>
    int main()
    {
    std::cout<<"\t\t"<<"a\n";
    std::cout<<std::setw(18)<<"a "; // And you add the a space here
    return 0;
    }
    

    And the output will be the same.


    The reason behind why should we put the \n or a space is because:

    It's because it justifies the whole two-character string "a"\n, not only the a. If you print the newline separately (... << 'a' << '\n') then you would get the same "error". You could also have solved it by using almost any space character, like ... << "a "; You might want to print both with and without the newline in the same program to see the difference. - Some Programmer Dude