所以挑战是用这个输出编写一个程序:
000042
420000
42
-42-
我的第一次尝试是这样的:
int fortyTwo = 42;
cout << setfill('0') << setw(6) << fortyTwo << endl;
cout << fortyTwo << setfill('0') << setw(6) << endl;
cout << fortyTwo << endl;
cout << setfill('-') << setw(4) << fortyTwo << setfill('-') << endl;
这给了我这样的东西:
000042
42
000042
42-- (sometimes just -42)
这是作者的解决方案:
cout << setfill('0') << setw(6) << 42 << endl;
cout << left << setw(6) << 42 << endl;
cout << 42 << endl;
cout << setfill('-') << setw(4) << -42 << endl;
为什么作者只使用一次setfill?setfill 如何在前两行工作,但在第 3 行突然停止?将 setfill('-') 和 setw(4) 放在 -42 之前如何产生 -42- 而不是--42?左对齐运算符需要什么?
最后为什么我的版本没有产生正确的输出?