2013-10-14 189 views
-1

我想要我的字符運行,以確定我的交換機是否運行。我無法放置循環的開始。 我正在使用整數選項和大小創建一個模式。該選項選擇模式類型1-4,大小決定了模式將具有的列數和行數。循環故障

#include <iostream> 
using namespace std; 
int main() 
{ 
int option, size; 
char run; 
cout << "This program is writen by Alex Walter. " 
    << "The purpose of this program is to create four different patterns of different sizes. " 
    << "The size of each pattern is determined by the number of columns or rows. " 
    << "For example, a pattern of size 5 has 5 columns and 5 rows. " 
    << "Each pattern is made up of character P and a digit, which shows the size. " 
    << "The size must be between 2 and 9. "; 

cout << "Menu" << endl 
    << "1. Pattern One " << endl 
    << "2. Pattern Two " << endl 
    << "3. Pattern Three " << endl 
    << "4. Pattern Four " << endl 
    << "0. Quit " << endl; 

cout << "Choose an option (between 1 and 4 or 0 to end the program): "; 
cin >> option; 
cout << "Choose a pattern size (between 2 and 9): "; 
cin >> size; 

do{ 
switch(run) 
{ 

case 1: 
      cout << "Pattern 1: " << endl << endl 
      << size << "PPPP" << endl 
      << "P" << size << "PPP" << endl 
      << "PP" << size << "PP" << endl 
      << "PPP" << size << "P" << endl 
      << "PPPP" << size << endl; 
break; 

case 2: 
      cout << "Pattern 2: " << endl << endl 
      << "PPPP" << size << endl 
      << "PPP" << size << "P" << endl 
      << "PP" << size << "PP" << endl 
      << "P" << size << "PPP" << endl 
      << size << "PPPP" << endl; 
      break; 

case 3: 
      cout << "Pattern 3: " << endl << endl 
      << "PPPPP" << endl 
      << "PPPP" << size << endl 
      << "PPP" << size << size << endl 
      << "PP" << size << size << size << endl 
      << "P" << size << size << size << size << endl; 
       break; 
case 4: 
      cout << "Pattern 4: " << endl << endl 
      << "PPPPP" << endl 
      << size << "PPPP" << endl 
      << size << size << "PPP" << endl 
      << size << size << size << "PP" << endl 
      << size << size << size << size << "P" << endl; 
       break; 
} 
cout << "Run again?" << endl; 
cin >> run; 
}while(run == 'y' || run == 'Y'); 


} 

我只寫了足夠的代碼來創建一個模式的例子。 但我也在尋找循環創建模式的方法。請不要只給我一個答案我真的想弄清楚這一點,我只是卡住了,並且沒有和我班上的任何學生聯繫。

+3

你在哪裏初始化'run'什麼嗎?你會得到未定義的行爲,因爲'run'永遠不會被初始化。我想你想要'switch'語句使用'option' –

+2

那些'cout'很可愛 – Kunal

+0

@Kunal你在開玩笑嗎? –

回答

1

您正在嘗試使用run有兩個不同的用途:

  1. 輸入「Y」或「Y」繼續運行,或「n」或「N」停止運行。
  2. 計算循環次數並在switch語句中使用以確定您正在運行哪個運行。

解決方法是有兩個單獨的變量。對於#2,使用run,但是您需要初始化它,這意味着在程序的最頂端給它一個初始值。要初始化,所提供的價值,你宣佈它,就像這樣:

int run = 1; 

通知我改變了類型從charint - 因爲你比較它的整數,而不是字符,在你開關的情況下,聲明。

現在確保每個循環都增加run(加1)。 (你也應該考慮會發生什麼,如果/當run達到5,這是不是在你的switch語句!)

++run; 

做到這一點的地方,如開關語句之後。

現在添加一個額外的變量,如input,並用它來代替run在那裏你正在輸入與cin並在while聲明它比較「Y」或「Y」的底部。您可以在上面變量聲明爲好,不需要初始化,儘管它是一個很好的習慣進入反正初始化:

char input = 'Y';