将文件传递给函数

Passing a file into a function

我正在尝试创建一个将文件传递给函数的程序。该函数应该检测我的文件中有多少行。我认为我没有将文件正确传递到我的函数中,我尝试了几种不同的方法。任何帮助将不胜感激。

#include <iostream>
#include <fstream>
#define die(errmsg) {cerr << errmsg << endl; exit(1);} 
using namespace std;

int num_of_lines(ifstream file)
{
    int cnt3;
    string str;

    while(getline(file, str))cnt3++;

    return(cnt3);
}


int main(int argc, char **argv)
{
    int num_of_lines(ifstream file);

    string file;
    file = argv[1];

    if(argc == 1)die("usage: mywc your_file"); //for some reason not working

    ifstream ifs;

    ifs.open(file);

    if(ifs.is_open())
    {
        int a;
        cout << "File was opened\n";

        a = num_of_lines(file);

        cout <<"Lines: " << a << endl;
    }
    else
    {
        cerr <<"Could not open: " << file << endl;
        exit(1);
    }

    ifs.close();

    return(0);
}

函数有两个问题。首先,您应该通过引用传递流。其次,你只是忘了初始化你的计数器。

int num_of_lines( ifstream &file )
{
    int cnt3 = 0;
    string str;
    while( getline(file, str) ) cnt3++;
    return cnt3;
}

另一件事是您将 file 传递给它(这是一个字符串)而不是 ifs。将调用更改为:

a = num_of_lines( ifs );