2016-02-25 150 views
-1

我目前正在研究一個項目,提示用戶輸入他們想要用於他們的盒子的高度,寬度和字符。我必須使用for循環創建一個實心和空心的盒子。我創造了一個沒有問題的堅實的人,但是當談到空心人時,我遇到了一些問題。任何幫助表示讚賞。C++如何用用戶輸入創建一個空心框/矩形?

int main() 

{ 
    int height; 
    int width; 
    int i, j; 
    char ch; 

    cout << "Please enter your height: "; 
    cin >> height; 

    cout << "Please enter your width: "; 
    cin >> width; 

    cout << "Please enter your character: "; 
    cin >> ch; 

    for (i = 1; i <= height; i++) 
    { 
     for (j = 1; j <= width; j++) 
      cout << ch; 
     cout << endl; 
    } 

    cout << "Press any key to continue to the next shape." << endl; 
    _getch(); 

    for (i = 1; i <= height; i++) 
    { 
     for (j = 1; j <= width; j++) 
     { 
      if (i == 1 || i == width -1 || j == 1 || j == height) 
       cout << ch; 
      else cout << " "; 
     } 
     cout << endl; 
    } 

    system("pause"); 
    return 0; 

} 
+0

「有些問題」是不是一個很好的問題陳述。請[編輯]您的問題以包含更具體的描述。 – Ajean

回答

1

你可以把它寫在嵌套的for循環:

if((i==1 || i==height) || (j==1 || j==width)) 
    cout << ch; 
else 
    cout << " "; 
+0

因此,我只是一個丁格爾,我不小心切換了我和j?感謝您的幫助! –

+0

不客氣。 :) –

0

這是編寫空心盒子的代碼。 w是寬度,h是高度,而c是要使用的字符。

int w, h; 
char c; 

int i, j; 

/* write the first line */ 
for (i = 0; i < w; ++i) 
    putchar(c); 
putchar('\n'); 

/* write the inner lines */ 
for (j = 0; j < h - 2; ++j) { 
    putchar(c); 
    for (i = 0; i < w - 2; ++i) 
     putchar(' '); 
    putchar(c); 
    putchar('\n'); 
} 

/* write the final line */ 
for (i = 0; i < w; ++i) 
    putchar(c); 
putchar('\n');