0

在这个小程序中,我只是将 4 个字符输出到文件中,然后检索它们。正如您在输出中看到的那样,while 循环仅读取 4 个字符,并且tellp 获得正确的位置,但一旦在外部tellp 获得-1。

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream out("E:\\test.txt");
    out << "1234";
    out.close();

    ifstream in("E:\\test.txt");

    int i=0;
    char ch;
    while(in.get(ch)){
        cout << "inside while loop ch="<< ch <<" and its position is " << in.tellg()<< endl;
        i++;
    }
    cout << "outside while loop ch="<< ch <<" and its position is " << in.tellg()<< " and int =" << i <<endl;
    return 0;
}

输出:

inside while loop ch=1 and its position is 1
inside while loop ch=2 and its position is 2
inside while loop ch=3 and its position is 3
inside while loop ch=4 and its position is 4
outside while loop ch=4 and its position is -1 and int =4

如果我使用:

while(in.get(ch) && in.peek() != EOF){
    cout << "inside while loop ch="<< ch <<" and its position is " << in.tellg()<< endl;
    i++;
}

输出:

inside while loop ch=1 and its position is 1
inside while loop ch=2 and its position is 2
inside while loop ch=3 and its position is 3
outside while loop ch=4 and its position is -1 and int =3

但是对于这种用法,我只得到除最后一个之外的所有字符。以及为什么我仍然在这里得到-1,之后我不能再“寻找”了?!!!!!!

我如何遍历 ifstream::get 并获取所有字符而不获取 EOF?

4

3 回答 3

2

在每个get()流位置之后移动。一旦到达文件末尾并尝试访问该位置的字符,流就会进入失败模式,即被std::ios_base::failbit设置。在失败模式下,流不会做任何事情,直到你调用clear().

请注意,调用tellg()是相当昂贵的。如果您想跟踪头寸,让计数器保持最新会便宜得多。

于 2013-09-21T18:10:15.100 回答
2

“我想再次寻找我不能的溪流”

你可以 :

利用:

in.clear(); //Clear flags
in.seekg(0); //seek to start

外部while

于 2013-09-21T18:11:27.053 回答
1

为什么我在这里仍然得到-1,之后我不能“寻求”了?

因为 while 条件评估为 false 并且failbit设置了

如果您想这样做并且您有固定数量的字符,那么您应该检查确切的字符数,而不是检查流的有效性。

于 2013-09-21T18:11:25.213 回答