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?
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';
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';
}
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
Your code wants a std::resetiosflags(std::ios::right)
sent to the output stream to undo the preceding std::setiosflags(std::ios::right)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With