Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 296
Vis Viva Avatar asked Mar 30 '12 17:03

Vis Viva


5 Answers

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';
like image 144
Jerry Coffin Avatar answered Oct 18 '22 10:10

Jerry Coffin


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';
}
like image 24
Robᵩ Avatar answered Oct 18 '22 10:10

Robᵩ


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
like image 36
Willem Avatar answered Oct 18 '22 10:10

Willem


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

like image 44
thb Avatar answered Oct 18 '22 09:10

thb


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
like image 42
jrok Avatar answered Oct 18 '22 10:10

jrok