c++ - 如何准确地按照要求格式化我的输出?

标签 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;
        }
    }
}

预期结果:

 * * *
  * *
   *

实际结果:

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

最佳答案

改变这个:

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

为此:

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

因为在主函数中不需要双循环,所以在第一个重载的 * 运算符中有内部循环。

关于c++ - 如何准确地按照要求格式化我的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503965/

相关文章:

c++ - 将结构传递给 unordered_map 时出现段错误

c++ - C++ 中的 const 变量

c++ - 仅为专用模板类定义转换运算符

c++ - clang 标准库错误或 C++ 未定义行为?

c++ - gsoap 作为 soap 客户端是线程安全的吗?

c++ - ctypes/C++ 段错误访问成员变量

c++ - 指向抽象类的指针的函数重载

c++ - 使用基类的派生类中定义的类型

c++ - 如何在c++中检查文件是否存在于Qt中

java - Java 和 C++ 对象的低延迟分布式缓存