c++setw

Why does \n mess up my column in C++ after using setw()?


Im in College and one of our projects in our software programing class was to prompt the user to input five different test scores, after which the program will calculate the average and display the individual scores along with the average in columns. i had an issue where setw(10) was displaying the proper spacing for everything except for the string "average".

i have since fixed this but was curious as to why my fix worked.

the original code was as follows:

cout << "\n\n" << setw(10) << "Test 1" << setw(10) << "Test 2" << setw(10) << "Test 3"
     << setw(10) << "Test 4" << setw(10) << "Test 5" << setw(10) << "Average\n\n";

its output looked like this:

    Test 1    Test 2    Test 3    Test 4    Test 5 Average

      77.0      78.0      89.0      87.0      67.0     79.60

i then deleted the \n's i had at the end and just put endl after the string and it was fixed:

    Test 1    Test 2    Test 3    Test 4    Test 5   Average
      78.0      78.0      67.0      78.0      56.0     71.40

what does \n do to mess with the spacing after using setw()?


Solution

  • what does \n do to mess with the spacing after using setw()?

    Of course, it does nothing.

    Look it at from the computer's point of view. The string "Average\n\n" has length 9. It does not matter that the final two characters are whitespace. The length is still 9.

    Your program asks the computer to output a string of length 9 in a field of width 10. So the computer outputs a single space, and then outputs "Average\n\n", expecting that the padding will effectively right-align the string.

    When you delete the two newline characters, the string length is shortened to 7. Now, the computer outputs 3 spaces of padding, and then the string "Average". This has the effect of right-aligning the string in a field that is 10 characters wide.