所以我已经创建了一个程序来创建一个正方形或矩形的框架,我试图让它在正方形/矩形内输出星星,所以它已经填满了一半。就像这样:
********
** * * *
* * * **
** * * *
********
到目前为止,这是我的代码:
void frameDisplay(int width, int height) {
cout <<"What should the width be?\n";
cin >> width;
cout <<"What should the height be?\n\n";
cin >> height;
if(width < 2){
cout <<"Width must be greater than two.\n";
cout <<"What should the width be? \n";
cin >> width;
}if(height < 2){
cout <<"Height must be greater than two.\n";
cout <<"What should the height be? \n";
cin >> height;
}
cout << string(width, '*') << endl;
for(int j = 0; j < height - 2; ++j)
cout << '*'<< string(width - 2, ' ')<< '*' << endl;
cout << string(width, '*') << endl;
}
int main(){
int width=0, height=0;
frameDisplay(width, height);
}
输出:
What should the width be?
5
What should the height be?
7
*****
* *
* *
* *
* *
* *
*****
答案 0 :(得分:0)
我建议您对代码进行一些重组。
创建单独的函数:
std::vector<std::vector<char>>
。然后从main
打电话给他们。
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
std::pair<int, int> getUserInput()
{
int width;
cout <<"What should the width be?\n";
cin >> width;
int height;
cout <<"What should the height be?\n";
cin >> height;
return std::make_pair(width, height);
}
void fillUpFrame(std::vector<std::vector<char>>& frameData)
{
// Add the logic to fill up the frame data.
}
对于displayFrame
,如果您有C ++ 11编译器,请使用:
void displayFrame(std::vector<std::vector<char>> const& frameData)
{
for ( auto const& row : frameData )
{
for ( auto cell : row )
{
cout << cell;
}
cout << endl;
}
cout << endl;
}
否则,请使用:
void displayFrame(std::vector<std::vector<char>> const& frameData)
{
suze_t rows = frameData.size();
for ( size_t i = 0; i < rows; ++i )
{
size_t cols = frameData[i].size();
for ( size_t j = 0; j < cols; ++j )
{
int cell = frameData[i][j];
cout << cell;
}
cout << endl;
}
cout << endl;
}
main
:
int main(){
// Get the user input.
std::pair<int, int> input = getUserInput();
int width = input.first;
int height = input.second;
// Create a 2D vector to hold the data, with all the elements filled up
// with ' '.
std::vector<std::vector<char>> frameData(height, std::vector<char>(width, ' '));
// Fill up the frame data.
fillUpFrame(frameData);
// Display the frame data
displayFrame(frameData);
return 0;
}