Anon
Anon

Reputation: 1354

Formatting the output stream, ios::left and ios::right

I have this code:

cout << std::setiosflags(std::ios::right);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

cout << std::setiosflags(std::ios::left);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

but the output doesnt come like i expected. instead of:

  1  2
1  2  

this comes out:

  1  2
  1  2

What is the problem? I set 'std::ios::left' but it makes no difference?

Upvotes: 9

Views: 20354

Answers (5)

Jerry Coffin
Jerry Coffin

Reputation: 490108

Unless you're feeling masochistic, just use:

// right justify by default.
cout << setw(3) << 1 << setw(3) << 2 << '\n';

// left justify
cout << std::left << setw(3) << 1 << setw(3) << 2 << '\n';

// right justify again.
cout << std::right << setw(3) << 1 << setw(3) << 2 << '\n';

Upvotes: 19

Willem
Willem

Reputation: 927

Use setf with a mask (no need for resetiosflags)

using namespace std;
cout.setf(ios::right, ios::adjustfield);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

cout.setf(ios::left, ios::adjustfield);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

Upvotes: 8

jrok
jrok

Reputation: 55395

Looks like if both left and right flags are set, the one that was set first takes precedence. If I explicitly reset right flag before setting left, I get the output you expected:

cout << std::setiosflags(std::ios::right);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

cout << resetiosflags(std::ios::right);

cout << std::setiosflags(std::ios::left);
cout << setw(3) << 1 << setw(3) << 2 << '\n'; // Output two values

Upvotes: 1

thb
thb

Reputation: 14454

Your code wants a std::resetiosflags(std::ios::right) sent to the output stream to undo the preceding std::setiosflags(std::ios::right).

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168626

You have to clear the previous value in adjustfield before you can set a new one.

Try this:

#include <iostream>
#include <iomanip>
int main () {
  std::cout << std::resetiosflags(std::ios::adjustfield);
  std::cout << std::setiosflags(std::ios::right);
  std::cout << std::setw(3) << 1 << std::setw(3) << 2 << '\n';

  std::cout << std::resetiosflags(std::ios::adjustfield);
  std::cout << std::setiosflags(std::ios::left);
  std::cout << std::setw(3) << 1 << std::setw(3) << 2 << '\n';
}

Upvotes: 8

Related Questions