2016-01-28 104 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