Not sure I understand what is going on with setw().

I would expect the program below to output something like this

77
 77
  77
   77
 
Instead, it does this:

77
77
77
 77
  77
   77

Why are the first three 77's not indented?

#include "utility.h"


// setw example
#include <iostream>
#include <iomanip>
using namespace std;

int main () 
{
  
	for(int i = 0; i < 10; i++)
	{
		cout << setw (i);
		cout << 77 << endl;
	}
		
		
	return 0;
}

Recommended Answers

All 4 Replies

How is line 15 working?

if you change line 12 to

for(int i = 2; i < 12; i++)

it seems to work

Why are the first three 77's not indented?

Consider the first three iterations of your loop:

cout << setw(0) << 77;
cout << setw(1) << 77;
cout << setw(2) << 77;

Now go see if you can figure out what happens when the length of the printed object meets or exceeds the set field width.

I think I figured it out.

The setw(n) is counting n spaces from the right side of the object. I was expecting it to be counting from the left.

Thanks guys.

Not quite. What setw() does is not indent the text; rather, it sets the field width of the text, with the right side of the text by default going to the rightmost column of the field (this is called 'right justified' text; you can explicitly set it to left-justify using the left manipulator). When you set the field size less than the size of the actual text going into the field, the text will in effect start at the beginning of the field and stick out past the end of the field.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.