如何准确格式化我的输出?

How can format my output exactly how it's asked?

本文关键字:输出 我的 格式化 何准确      更新时间:2023-10-16

我的输出应该是使用星星的向下箭头。

但是,它不起作用,我是C++新手,不知道如何操作循环。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string operator*(const string& s, unsigned int n) {
    stringstream out;
    while (n--)
        out << s;
    return out.str();
}
string operator*(unsigned int n, const string& s) { return s * n; }
int main(int, char **)
{
    string space = " ";
    string mix = "* ";
    for (int i = 0; i<3;i++)
    {
        cout << space*i;
        for (int j = 3; j>= 0; --j)
        {
            cout <<mix*j << endl;
        }
    }
}

预期成果:

 * * *
  * *
   *

实际结果:

* * *
* *
*
 * * *
* *
*
  * * *
* *
*

更改以下内容:

cout << space*i;
for (int j = 3; j>= 0; --j)
{
    cout <<mix*j << endl;
}

对此:

cout << space * i;
cout << mix * (3 - i) << endl;

由于主函数中不需要双循环,因此在第一个重载*运算符中具有内部循环。

相关文章: