暗影和决斗者:c++问题,使用tellg()以后getline()读取不正确

来源:百度文库 编辑:神马品牌网 时间:2024/05/06 08:52:50
打开一个文本文件,显示内容不一致。注释掉tellg那一行以后正常,这是为什么?

#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;
int main(int argc,char * argv[]){
if(argc>=2){
cout<<argv[1]<<endl;
ifstream fin(argv[1]);
if(!fin.fail()){
string str;
int i = 0;
//getline(fin,str);
while(!fin.eof()){
//cout<<"("<<fin.tellg()<<")";
getline(fin,str);

cout<<++i<<":"<<str<<endl;
//cout<<"("<<fin.tellg()<<")"<<endl;
}
cout<<"total lines:"<<i<<endl;
}
}
cout<<endl;
tanyuguo的文本太短,如果每一行的文本长一些问题就出来了

没发现什么不一致啊。我建了一个简单的文本文件
1a
2b
3c
4d
不用tellg那行的话,显示
1:1a
2:2b
3:3c
4:4d
total lines:4
用的话,显示
(0)1:1a
(4)2:2b
(8)3:3c
(12)4:4d
total lines:4
都正常啊