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>
usingnamespace 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.
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...)