为什么左对齐在循环的第一次迭代中不起作用?

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;
 }

这是我的代码。据我所知,它应该从屏幕最左边打印 s1 和 s2 20 个字符。但是,它打印

        Some String:Hello1
Another String:     Hello2

Some String:        Hello1
Another String:     Hello2

Some String:        Hello1
Another String:     Hello2

我按照老师的指示使用onlineGDB编译。我犯了什么错误?

这句话说的是

cout.width(20); cout<<"Some String:"<<left<<s1<<endl;

set column width to 20,
output "Some String:"
start left justifying
output s1
output end of line 

你是说

cout.width(20);
cout << left;
cout<<"Some String:" << s1 << endl;

std::left 是一个“粘性”操纵器,意味着您只需设置一次。默认情况下,填充的字符串将为 right-justified,这是在应用 std::left 操纵器之前输出 "Some String:" 时发生的情况。

请参阅 documentation,其中指出:

The initial default for standard streams is equivalent to right.

正在修复您的代码,并稍微整理一下:

#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;
}

输出:

Some String:        Hello1
Another String:     Hello2

Some String:        Hello1
Another String:     Hello2

Some String:        Hello1
Another String:     Hello2

请注意,我使用了 <iomanip> 中的 std::setw I/O 操纵器,而不是对 cout.width() 的调用。这使代码更易于阅读和遵循。

参见 documentation std::setw