setw() not working properly why ??

Hello everyone

I have started C++ few weeks ago and just signed for this forum for some help and any advices I will need in the future:) Also I have got one question already :)

Below provided code use setw() in first line of the code you can see that it should display 100 but for some reason it still show 1000. Can someone explain my why ?? According to all books and forums this should work but it does not.

I am using Windows 7 with Dev C++ 4.9.9.2

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    cout << "It should display 100 but it shows " << setw(3) << 1000 << endl;
    cout << setw(5) << "It should display 1000 and it does show " << 1000 << endl;   
    cout << endl;
system ("PAUSE");  
}  
}

setw() does not limit the text AFAIK, it only sets the minimum width they can take. So if you setw(1) then try to print 500, it will still print the whole number. Btw, you have an extra } at the end of your program.
I am sorry firedraco but could you please explain it bit more clearly as I am not getting it :(

some example would be nice :):):):)

Cheers
it means, that if u have set it to a higher number of characters than ur text/number would need, it would still use number set to by setw()...

e.g.

cout << setw(5) << 1;
1****
where * is the fill character set by setfill()...

cout << setw(1) << 10000;
10000
Last edited on
Don't blame the tools for your errors. setw works exactly as it is designed.
http://www.cplusplus.com/reference/iostream/manipulators/setw/

The field width determines the minimum number of characters to be written in some output representations
bold emphasis added

There is, unfortunately, no manipulator to uniformly limit the maximum width of fields. (The setprecision manipulator is for floating-point operations.) You could write your own, but it would probably just be easier to use an ostringstream directly and truncate it if it is too large.

(This seems like an interesting project. Maybe I'll write something for you...)
Topic archived. No new replies allowed.