0

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 7
    Tabs and width adjusting is ***not*** the same. Tab typically goes to fixed positions in the terminal, usually 8, 16, 24, etc. The newline should not matter. – Some programmer dude Jul 02 '22 at 08:53

1 Answers1

0

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

  • 5
    Do you know *why* the newline matter here? 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 Jul 02 '22 at 10:48