![](/img/trans.png)
[英]How to format text using std:out setfill std::setw std:right with one padding space
[英]How to print this pattern in C++ without using `std::setw`, `std::left` and `std::right`
我必须编写一个C ++程序来打印此模式:
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
这是我的解决方案:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
for(int i = 1; i <= 5; ++i) {
string temp = "";
for(int j = 1; j <= i; ++j) {
if(j == i)
temp += "*";
else
temp += "* ";
}
cout << left << setw(10)<< temp;
cout << right << setw(10) << temp << endl;
}
return 0;
}
是否有仅使用简单空格的解决方案? 不要只在cout
语句中写五个字符串。
如果使用两个字符串变量,例如left
和right
,而不是单个temp
变量,则可以轻松实现:
for(int i = 0; i < 5; i++)
{
string left, right;
for(int j = 0; j < 5; j++)
{
if(j - i < 1)
{
// Add a star and a space to each side.
left += "* ";
right = " *" + right;
}
else
{
// Add four spaces into the middle between the stars.
left += " ";
}
}
cout << left + right << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.