修复行读取功能的语法

时间:2015-07-29 07:29:08

标签: c++ function ifstream

我之前尝试制作一个程序,告诉用户然后文本文件中的字符,单词和行数。我做了函数来确定每个的数量,但我按值传递它们。这导致了一个错误,因为在读取了char的数量后,它将在文件的末尾,然后为其他两个输出零。现在我似乎无法重写我的函数,以便每次检查文件时都会打开和关闭char,单词和行。任何人都看到我的错误在哪里?谢谢! (现在只复制并粘贴了我的一个功能)。

int num_of_lines(ifstream file)
{
    string myfile;
    myfile = argv[1];

    ifstream l;
    l.open(myfile);

    int cnt3 = 0;
    string str;

    while(getline(file, str))cnt3++;
    l.close();

    return(cnt3);
}


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

    string file;
    file = argv[1];

    if(argc == 1)die("usage: mywc your_file"); 

    ifstream ifs;

    ifs.open(file);

    if(ifs.is_open())
    {
        int a, b, c;

        a = num_of_lines(ifs);

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

    ifs.close();

    return(0);
}

1 个答案:

答案 0 :(得分:0)

没有办法重新打开&#34;除了知道名称和创建新ifstream之外的文件,但您可以使用seekg成员函数在文件中设置读取位置,将其设置为0将使下一个读取操作开始从文件的开头。

无法复制流,因此您无法通过值&#34;传递它,但必须通过引用传递它。

int num_of_lines(ifstream &file)
{
    int count = 0;
    string str;

    while (getline(file, str)) {
        count++;
    }
    file.seekg(0);

    return count;
}

对于完整的问题,我同意Mats Petersson的观点。在一次通过中对字符,行和单词进行计数将比在文件中读取三次更有效。

相关问题