#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 进行编译。我犯了什么错误?
std::left
是一个“粘性”操纵器,这意味着您只需设置一次。默认情况下,填充字符串将是右对齐的,这是在应用操纵器"Some String:"
之前输出时发生的情况。std::left
请参阅文档,其中指出:
标准流的初始默认值相当于
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
请注意,我使用std::setw
I/O 操纵器 from<iomanip>
而不是调用cout.width()
. 这使代码更易于阅读和遵循。
请参阅文档std::setw
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句