2017-01-24 43 views
-6

我想問一個很簡單的問題,有時會讓我迷惑。如何從子程序functrion返回值到主函數?

我想從子程序功能的價值,但我試了很多辦法還是不要把它弄出來,

這裏是我的代碼:

void Read_line (string filename) 
{ 
    int number_of_lines = 0; 
    std::string line1; 
    std::ifstream myfile(filename.c_str()); 

    while (std::getline(myfile, line1)) 
    { 
     ++number_of_lines; 
    } 
    cout << "Number of lines in text file: " << number_of_lines; 

// return number_of_lines; 
} 

int main() 
{ 

    string name = "gbm"; 
    double WEEK = 1930; 
    double DAY = 0; 

    string week = boost::lexical_cast<string>(WEEK); // convert number to string 
    string day = boost::lexical_cast<string>(DAY) ; // convert number to string 

    string filename = name + week + day + ".sp3"; 
    int number_of_lines = Read_line(filename); 

    // my expectation to have "number_of_lines" value in here 

    cout << "Number of lines in text file: " << number_of_lines; 

} 

感謝您的幫助。

+0

任何C教程都應該解釋如何獲取函數的結果。該函數需要使用'return'語句,並且您需要更改函數聲明以說明它返回的類型。 – Barmar

+1

您不能返回除函數聲明的 –

+1

@ChristianHackl以外的其他類型,顯然是因爲代碼被複制,而且老師懷疑代碼的作者身份後給出了另一個補充。 – SergeyA

回答

3

更改函數返回int而不是void。然後,您可以取消註釋return聲明。

int Read_line (string filename) 
{ 
    ... 
    return number_of_lines; 
}