如何从子程序functrion获取返回值到main函数?

时间:2017-01-24 21:57:12

标签: c++

我想问一个非常简单的问题,有时会让我感到困惑。

我想从子程序函数中获取一个值,但我尝试了很多方法仍然没有把它弄出来,

这是我的代码:

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;

}

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

更改功能以返回int而不是void。然后,您将能够取消注释return语句。

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