简体   繁体   中英

Using setw is failing inside of a for loop

Suppose there is an array of structs called machine with elements drink, price.

for(int i = 0; i < 10; i++)
{
    cout << i+1 << ". " << machine[i].drink;
    cout << setw(20) << machine[i].price << "\n";
}

This isn't working the way I would normally expect setw to work, and it's formatting my spaces in much the same way that \\t would do (not creating columns but rather uneven spacing).

Any help here?

You're setting the width for the incorrect output.

As written, your setw(20) starts after the machine[i].drink; output. So if you want to print Coke for $1.00 , you'd see Coke followed by 15 fill characters for spaces, then $1.00 as the last 5 characters of the setw(20) . But if you wanted to print Mountain Dew for $1.00 , you'd again see Mountain Dew followed by the same 15 fill characters, then $1.00 .

What you need is the fill characters to be appended to the end of the machine[i].drink output, but currently you're putting them at the beginning of the machine[i].price output.

You should be using setw() on the first output and left justifying it. Then output the price without a setw() or justification.

For example:

cout << setw(20) << left << i+1 << ". " << machine[i].drink;
cout << machine[i].price << "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM