2016-01-28 68 views
-3

SO我已经创建,创建一个正方形或长方形的框架,我试图得到它的正方形/长方形内输出恒星的程序,所以它是半满的,像这样的:C++创建一个半满的矩形

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

这里是我到目前为止的代码:

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 
***** 
* * 
* * 
* * 
* * 
* * 
***** 
+1

而问题将是...? – SergeyA

+0

你的输出是什么? – MASh

+0

如何让我的代码输出上面的图片,而不是像我的代码创建一个框架 – SillyPenguin420

回答

0

我建议有点restruc的你的代码的图灵。

创建独立的功能:

  1. 接受用户输入。
  2. 填写框架数据在std::vector<std::vector<char>>
  3. 显示帧数据。

然后从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; 
} 
+0

非常感谢您的回复。由于某种原因,我无法得到它在我的系统编译 – SillyPenguin420

+0

我忘了'#包括'。该文件具有'std :: pair'的定义。 –

+0

好吧谢谢你生病了吧 – SillyPenguin420