2

If I write code like this:

int a = 123456; cout << setw(20) << setiosflags(ios::right) << a << endl; cout << setiosflags(ios::left) << setw(20) << a << '*' << endl; 

On the 3rd line, I set the alignment as left align, so my expected output is

 123456 123456 *

but the REAL output is

 123456 123456* 

Why did that happen?

The IDE I use is DevCpp.

0

4 Answers 4

3

std::setiosflags() sets new flags without clearing any existing flags. So on the 3rd line, you are enabling the ios::left flag without disabling the ios::right flag. It does not make sense to have both flags enabled at the same time, and it seems the stream prefers the ios::right flag if it is enabled.

Use std::left and std::right instead. They reset the ios::internal, ios::left, and ios::right flags before setting the new alignment.

int a = 123456; cout << setw(20) << right << a << endl; cout << left << setw(20) << a << '*' << endl; 

Live demo

Sign up to request clarification or add additional context in comments.

1 Comment

Since it doesn't make sense,I think the compilor should useios::leftto cover ios right
0

If you remove the line with setiosflags(ios::right), it works as expected, so it seems all common compilers evaluate right before left and short circuit the program flow. Try either manually unsetting ios::right, or better yet, just use std::left like so:

cout << left << setw(20) << a << '\n'; 

This, as so many standard library functions, takes care of pesky details.

Comments

0
int a = 123456; cout.setf(ios::right, ios::adjustfield); cout << setw(20) << a << endl; cout.setf(ios::left, ios::adjustfield); cout << setw(20) << a << '*' << endl; 

If I recall, you need to reset the alignment.

Comments

0

The setiosflags sets format flag for the output stream (here it's cout), not for this sentence only. Since the ios::right has priority over ios::left, the second line will be aligned right. So you need to clear the previous format flag and then set the new one.

int a = 123456; cout << setw(20) << setiosflags(ios::right) << a << endl; cout << resetiosflags(ios::right) << setiosflags(ios::left) << setw(20) << a << '*' << endl; 

But the simplest way is to use std::left and std::right

int a = 123456; cout << setw(20) << right << a << endl; cout << left << setw(20) << a << '*' << endl; 

1 Comment

So setiosflags sets the format flag for the program ,does setiosflags(ios::setw(20))sets the width for the whole program?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.