在这个小程序中,我只是将 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?