如何完全按照要求格式化输出?

时间:2019-02-03 14:41:51

标签: c++

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

但是,它不起作用,并且我是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;
        }
    }
}

预期结果:

 * * *
  * *
   *

实际结果:

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

1 个答案:

答案 0 :(得分:0)

更改此:

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

对此:

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

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