我不知道为什么ios::right
工作一次。完全没有
ios::hex
, ios::decimal
和其他一些人也有同样的问题,除非我做一些疯狂的代码并让它们神奇地再次工作
#include <iostream>
#include <iomanip>
using std::cout;
using std::ios;
int main() {
int len;
std::cin >> len;
// w = len + 1;
cout.width(len);
cout.setf(ios::right);
for (int s = 0; s < len; s++) {
for (int c = 0; c <= s; c++) {
cout << '#';
}
cout << 'n';
}
std::cin.get();
std::cin.get();
}
预期输出: #
##
###
####
#####
######
结果:
#
##
###
####
#####
######
try This:
cout << ios::right << '#';
没有工作。
您需要在第一个循环中编写cout.width(len-s);cout.setf(ios::right);
,因为ios::right只工作一次。所以应该是
#include <iostream>
#include <iomanip>
using std::cout;
using std::ios;
int main()
{
int len;
cin >> len;
for (int s = 0; s < len; s++)
{
cout.width(len);
cout.setf(ios::right);
for (int c = 0; c <= s; c++)
{
cout<<"#";
}
cout<<"n";
}
std::cin.get();
std::cin.get();
}
但是你的代码是不正确的,根据你需要的输出,正确的代码是:
#include <iostream>
#include <iomanip>
using std::cout;
using std::ios;
int main()
{
int len;
cin >> len;
for (int s = 0; s < len; s++)
{
cout.width(len-s); // to align properly
cout.setf(ios::right);
for (int c = 0; c <= s; c++)
{
cout<<"#";
}
cout<<"n";
}
std::cin.get();
std::cin.get();
}
这里的问题不是right
是临时的,而是width
是临时的,所以下一个字符输出不使用给定的宽度-事实上这是一件好事,或者你的第二行将是# #
,所以你可能不想要!
解决方案是将width
调用移动到两个循环的外部(并在输出越来越宽时相应地重新计算宽度)。
我故意不写你应该怎么做,因为你需要练习思考事情是如何工作的,而不是练习CTRL-C/CTRL-V
。
一个更短更简单的方法来做你想做的事情
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
for (int j = n; j > 0; --j)
cout << (i >= j ? "#" : " ");
cout << endl;
}
return 0;
}
输入6
#
##
###
####
#####
######