[英]Print out the alphabet using for loop and setw
When I compile my program, run it and enter values I will get a rather strange and unexpected output:当我编译我的程序,运行它并输入值时,我会得到一个相当奇怪和意想不到的 output:
So if I enter:所以如果我输入:
Enter width and height: 9 5
Enter characters: X O
1 XOXOXOXOX
2 OXOXOXOXO
3 XOXOXOXOX
4 OXOXOXOXO
5 XOXOXOXOX
A BCDEFGHI
When it's supposed to be:当它应该是:
Enter width and height: 9 5
Enter characters: X O
1 XOXOXOXOX
2 OXOXOXOXO
3 XOXOXOXOX
4 OXOXOXOXO
5 XOXOXOXOX
ABCDEFGHI
When do my void print_alphabet
in another program it will work out just fine so I don't know the problem.我的
void print_alphabet
什么时候在另一个程序中运行它会很好,所以我不知道问题所在。 I believe it has something to do with my other function but I can not seem to get it to work.我相信它与我的其他 function 有关,但我似乎无法让它工作。 Why does it act that way?
为什么它会那样做? Why does it print out A and then it does setw and prints out the rest?
为什么它打印出 A 然后它确实设置并打印出 rest?
This is my code:这是我的代码:
#include <iostream>
#include <iomanip>
using namespace std;
void print_chess_board (int const height,
int const width,
char const char_1,
char const char_2)
{
int index {};
for (int i = 1; i <= height; ++i)
{
if (i%2)
{
index = 0;
}
else
{
index = 1;
}
cout << left << setw(3) << i;
for (int j {}; j < width; ++j)
{
if (++index%2 == 0)
{
cout << char_2;
}
else
{
cout << char_1;
}
}
cout << endl;
}
}
void print_alphabet (int const width)
{
cout << setfill(' ') << setw(4);
for (int i {}; i < width; ++i)
{
cout << char('A' + i);
}
}
int main()
{
int width {};
int height {};
char char_1 {};
char char_2 {};
cout << "Enter width and height: ";
cin >> width >> height;
cout << "Enter characters: ";
cin >> char_1 >> char_2;
print_chess_board(height,width,char_1,char_2);
print_alphabet(width);
return 0;
}
You need to change你需要改变
cout << setfill(' ') << setw(4);
to至
cout << right << setfill(' ') << setw(4);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.