[英]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). 这不像我通常期望setw那样工作,并且格式化空间的方式与\\ t差不多(不是创建列,而是间隔不均匀)。
Any help here? 这里有什么帮助吗?
You're setting the width for the incorrect output. 您正在为错误的输出设置宽度。
As written, your setw(20)
starts after the machine[i].drink;
如所写,您的
setw(20)
在machine[i].drink;
之后启动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)
. 因此,如果您要以
$1.00
的$1.00
打印Coke
,则会看到Coke
后跟15个填充字符,然后是$1.00
作为setw(20)
的最后5个字符。 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
. 但是,如果您想以
$1.00
的$1.00
打印Mountain Dew
,则会再次看到Mountain Dew
后跟相同的15个填充字符,然后是$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. 您需要的是将填充字符附加到
machine[i].drink
输出的machine[i].drink
,但是当前您将它们放在machine[i].price
输出的开头。
You should be using setw()
on the first output and left justifying it. 您应该在第一个输出上使用
setw()
并使其对齐。 Then output the price without a setw()
or justification. 然后输出没有
setw()
或理由的价格。
For example: 例如:
cout << setw(20) << left << i+1 << ". " << machine[i].drink;
cout << machine[i].price << "\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.