繁体   English   中英

如何在不使用`std :: setw`,`std :: left`和`std :: right`的情况下在C ++中打印此模式

[英]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语句中写五个字符串。

如果使用两个字符串变量,例如leftright ,而不是单个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM