我的输出应该是一个使用星号的向下箭头。
但是,它不起作用,我是 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/