2012-11-09 46 views
0

我的任務是編寫一個程序,根據用戶輸入的數據顯示星號(*)的字段。我得到了代碼工作,但我的老師要求他們至少有兩個功能。 displaybanner功能不起作用。 getData運行並要求用戶輸入值,但程序在輸入後停止。什麼似乎出錯?功能顯示問題

#include <iostream> 

using namespace std; 

void displaybanner(int numrows=0, int numcolums=0, int numfields=0); 

void getData(int numrows=0, int numcolumns=0, int numfields=0); 

const char c = '*'; 



int main(void) 
{ 
    getData(); 
    displaybanner(); 


} 

void getData(int numrows,int numcolumns,int numfields) 
{ 

    cout << "Welcome to the banner creation program!" << endl; 

    cout << "Enter the number of rows (1 - 5) --> "; 
    cin >> numrows; 

    if(numrows<1 || numrows>5){ 
     cout << "Your entered value is outside the range!" << endl; 
     cout << "Program will now halt..." << endl; 
     exit(0);} 


    cout << "Enter the number of columns (5 - 50) --> "; 
    cin >> numcolumns; 

    if(numcolumns<5 || numcolumns>50){ 
     cout << "Your entered value is outside the range!" << endl; 
     cout << "Program will now halt..." << endl; 
     exit(0); 
    } 

    cout << "Enter the number of rows (3 - 10) --> "; 
    cin >> numfields; 

    if(numfields<3 || numrows>10){ 
     cout << "Your entered value is outside the range!" << endl; 
     cout << "Program will now halt..." << endl; 
     exit(0); 
    } 

} 

void displaybanner(int numfields, int numrows, int numcolumns) 
{ 
for (int i = 0; i < numfields; i++) { 
    for (int j = 0; j < numrows; j++) { 
    for (int k = 0; k < numcolumns; k++) { 
     cout << c; 
    } 
    cout << endl; 
    } 
    cout << endl << endl << endl; 
} 
} 
+0

考慮函數的參數意味着什麼。特別是,如果你不給'getData()'任何東西,它將打印0星,即沒有任何東西。 – BoBTFish

回答

2

這不起作用,因爲您只是在您的函數中修改臨時/本地值。要解決這個問題,你必須通過引用傳遞你的參數(使用指針或引用)。

最簡單的方法可能是使用引用,例如,改變

void getData(int numfields, int numrows, int numcolumns) 

void getData(int &numfields, int &numrows, int &numcolumns) 

這將保證讓你對這些參數的所有更改,返回給調用函數時也是如此。請注意,您不能使用默認參數,但您只需在要通過參數返回值的位置執行此操作。然後

你的主要功能應該是這樣的:

int main(void) 
{ 
    int fields, rows, cols; 
    getData(fields, rows, cols); 
    displaybanner(fields, rows, cols); 
} 
0

默認參數displaybanner都是零:

void displaybanner(int numrows = 0, int numcolums = 0, int numfields = 0); 

而且,由於我們在調用主模塊中這個功能沒有任何參數,循環的繼承將不會執行(因爲索引變量爲0且它們的限制爲0)。要使其工作,請將參數傳遞給displaybanner或使其缺省參數大於0.