为什么在循环的第一次迭代中,剩余的理由不起作用?
#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
根据我的老师的指示,它打印了我使用在线GDB进行编译的印刷。我犯了什么错误?
#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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std::left
是一个“粘性”操纵器,这意味着您只需设置一次。默认情况下,填充的字符串将右对齐,这就是在应用std::left
操纵器之前输出"Some String:"
时发生的情况。请参阅文档,其中指出:
修复您的代码,并稍微整理一下:
输出:
请注意,我使用了
中的std::setw
I/O 操纵器,而不是调用 <代码>cout.width()。这使得代码更容易阅读和遵循。请参阅 文档了解
std::setw
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 thestd::left
manipulator.See the documentation which states:
Fixing your code, and tidying it up a bit:
Output:
Note that I used
std::setw
I/O manipulator from<iomanip>
instead of the call tocout.width()
. This makes the code easier to read and follow.See the documentation for
std::setw
该陈述说
你的意思是
this statment says
you mean