c++coutjustify

Why does left justification not work in the first iteration of a loop?


#include <iostream>

int main(){
       using namespace std;

       string s1("Hello1");
       string s2("Hello2");
       
       for(int i = 0; i < 3; i++){
           
           cout.width(20); cout<<"Some String:"<<left<<s1<<endl;
           cout.width(20); cout<<"Another String:"<<left<<s2<<endl;
           
           cout<<endl;
       }
       return 0;
 }

Here is my code. It, to my knowledge, should print s1 and s2 20 characters from the very left of the screen. However, it prints

        Some String:Hello1
Another String:     Hello2

Some String:        Hello1
Another String:     Hello2

Some String:        Hello1
Another String:     Hello2

I am using onlineGDB to compile, as per instruction of my teacher. What error am I making?


Solution

  • std::left is a "sticky" manipulator, meaning you just set it once. By default, padded strings will be right-justified, which is what happens when you output "Some String:" before ever applying the std::left manipulator.

    See the documentation which states:

    The initial default for standard streams is equivalent to right.

    Fixing your code, and tidying it up a bit:

    #include <iostream>
    #include <iomanip>
    
    int main()
    {
        using namespace std;
    
        string s1("Hello1");
        string s2("Hello2");
    
        cout << left;       
        for(int i = 0; i < 3; i++) {
            cout << setw(20) << "Some String:" << s1 << endl;
            cout << setw(20) << "Another String:" << s2 << endl;
            cout << endl;
        }
        return 0;
    }
    

    Output:

    Some String:        Hello1
    Another String:     Hello2
    
    Some String:        Hello1
    Another String:     Hello2
    
    Some String:        Hello1
    Another String:     Hello2
    
    

    Note that I used std::setw I/O manipulator from <iomanip> instead of the call to cout.width(). This makes the code easier to read and follow.

    See the documentation for std::setw