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

放肆的年华 提交于 2021-02-08 13:14:23

问题


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?


回答1:


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';
}



回答2:


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';



回答3:


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



回答4:


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




回答5:


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


来源:https://stackoverflow.com/questions/9947336/formatting-the-output-stream-iosleft-and-iosright

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!