setw trouble

Hi,

I'm trying to cout two arrays with right setw, but I can't get it to work correctly. I've tried this....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int i = 0;

while (i < howMany){
    cout << fixed << right;
    cout << setfill(' ') << setw(80) << menuItems[i] ;
    cout << fixed << right;
    cout << " $: " << menuPrices[i] << endl;
    cout << string(80, ' ');
    i++;
    cout << string(80, ' ');
}

// Which works only on arrays at position [0]. 
// I've also tried..

/*for (int i = 0; i < howMany; i++){
    cout << fixed << setw(80) << right << menuItems[i] << " $: " << 
    menuPrices[i] << endl;
}
which does the same thing.*/



Thank you.
Last edited on
You need setw() before each output. At the moment you are only doing it before the first.
Like this?

1
2
3
4
5
6
7
8
9
10
   
int i = 0;

while (i < howMany){
   
    cout << setw(80) << menuItems[i] ;
    cout << setw(80) << " $: " << setw(80) << menuPrices[i] << endl;
    i++;
    
}


Thank you.
Good job!

Sometimes you will want to compose a string and justify all of that.
This is where std::stringstream comes in handy.

1
2
3
4
5
6
7
8
9
10
// A name
auto surname = "Dupain-Cheng";
auto given_name = "Marinette";

// Now, to compose the name
std::ostringstream ss;
ss << surname << ", " << givenname;

// And now to output it into a left-justified 30-character wide (but no more!) space:
std::cout << "[" << std::left << std::setw( 30 ) << ss.str().substr( 30 ) << "]\n";

Output
[Dupain-Cheng, Marinette       ]

Hope this helps now and in the future. :O)
Last edited on
Topic archived. No new replies allowed.