Trying to set max output width

Hey guys,

I'm messing around with setw(), trying to make use of it, but it doesn't seem to be working.
I'm pretty sure I understand the syntax and use of setw(), having looked it up in a couple of references, and several online forum posts etc. It's not rocket science, so I'm not sure why this isn't doing what I want it to.
This is what my code looks like:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
    cout << "This is a line.\n";
    cout << setw(5) << "This line should be set to display 5 chars per line :)";
    cin.ignore(80, '\n');

and here's what the output looks like:

This is a line.
This line should be set to display 5 chars per line :)

So, honestly, what the crap? What am I missing?

Thanks for any suggestions.
Last edited on
Can i know what kind of ouput you needed?
The setw() pads the output with the number of characters specified. It doesn't truncate an entry that is larger than the pad size. So if your string was less than 5 characters it would add enough characters to occupy 5 spaces in the output. Note the padding character is usually a space but can be changed with the setfill() function.

Last edited on
Thanks, jlb. Clearly I was confused.

That said, it seems that I need an easy method to set the maximum width of program output.

Any ideas?
Last edited on
Since you're using a constant you should create a string to hold the information and then either use the substr() function to print the desired number of characters or truncate this string to the proper length using std::string.erase().
Topic archived. No new replies allowed.