So the challenge is to write a program with this output:
000042
420000
42
-42-
My first attempt was something like this:
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;
Which gave me something like this:
000042
42
000042
42-- (sometimes just -42)
Here is the author's solution:
cout << setfill('0') << setw(6) << 42 << endl;
cout << left << setw(6) << 42 << endl;
cout << 42 << endl;
cout << setfill('-') << setw(4) << -42 << endl;
Why does the author only use setfill once? How does setfill work for the first two lines but stop all of a sudden at line 3? How does putting setfill('-') and setw(4) before -42 produce -42- instead of --42? What is the left alignment operator needed for?
Finally why doesn't my version produce the correct output?