2013-11-04 24 views
1

下面的代碼打印出用戶輸入的整數框。我需要讓它變成空心的,只顯示框的第一行和最後一行的全長。像寬度= 5高度= 4如何在for循環中創建異常?

示例輸出:

00000 
0 0 
0 0 
00000 

來源:

int main() 
{ 
    int height; 
    int width; 
    int count; 
    int hcount; 
    string character; 

    cout << "input width" << endl; 
    cin >> width; 
    cout << "input height" << endl; 
    cin >> height; 
    cout << "input character" << endl; 
    cin >> character; 

    for (hcount = 0; hcount < height; hcount++) 
    { 
     for (count = 0 ; count < width; count++) 
      cout << character; 
     cout << endl; 
    } 
} 

我不知道如何改變循環條件爲寬度,使其工作。

+0

打印'character'然後打印'寬度 - 2'空間然後打印另一'character'。 –

回答

0

將一個if添加到cout << character行。如果我們不在第一行或第一列,輸出一個空格而不是字符。

2

我想你可以測試你是否在第一行或最後一行,以及第一列或最後一列。

實施例:

#include <string> 
#include <iostream> 

int main() 
{ 
    using namespace std; // not recommended 

    int height; 
    int width; 
    string character; 

    cout << "input width" << endl; 
    cin >> width; 
    cout << "input height" << endl; 
    cin >> height; 
    cout << "input character" << endl; 
    cin >> character; 

    for (int i = 0; i < height; i++) 
    { 
    // Test whether we are in first or last row 
    std::string interior_filler = " "; 
    if (i == 0 || i == height - 1) 
    { 
     interior_filler = character; 
    } 

    for (int j = 0; j < width; j++) 
    { 
     // Test whether are in first or last column 
     if (j == 0 || j == width -1) 
     { 
     cout << character; 
     } else { 
     cout << interior_filler; 
     } 
    } 
    // Row is complete. 
    cout << std::endl; 
    } 
} 

這裏是輸出:

$ ./a.out 
input width 
10 
input height 
7 
input character 
* 
OUTPUT 
********** 
*  * 
*  * 
*  * 
*  * 
*  * 
**********