c++ fstream 在 1 个函数之后不起作用(通过引用)

c++ fstream dosent work after 1 function (by refrence)

您好,我正在尝试计算 txt 文件中的行数和字符数,在 1 个计算行数的函数(有效)之后,字符计数器开始工作,但如果我单独使用字符计数器,它就可以工作. (我知道我可以将它混合到一个函数中,但我有一个更大的问题需要这个示例来解决)

主要:

int main()
{
    ifstream isf("D:\test.txt", ios_base::in);
    ofstream osf("D:\test.txt", fstream::app);
    //WriteToFile(osf,isf);
    cout << CountLines(isf)<< endl;
    cout << CountChar(isf) <<endl;
    isf.close();
    osf.close();
    return 0;
}

函数:

const int CountLines(ifstream& isf)
{
    int count = 1;
    char c;
    while (isf.get(c))
    {
        if (c == '\n')
            ++count;
    }
    return count;
}
const int CountChar(ifstream& isf)
{
    int count = 0;
    char c;
    while (isf.get(c))
    {
        ++count;
    }
    return count;
}

txt 文件:

abc
abc

输出:

2
0
Press any key to continue . . .

输出应该是

2
7
Press any key to continue . . .

您必须在调用第一个函数后将流重置到起始位置:

cout << CountLines(isf)<< endl;
isf.clear(); // Reset stream states like eof()
isf.seekg(0); // <<<<<<<<<<<<<<<<<<
cout << CountChar(isf) <<endl;