c++中ifstream读文件的问题(关于eof())
2014-04-21 22:25
489 查看
今天帮别人找BUG,是一段关于c++读写文件的问题,使用的是ifstream与outstream类,关于ofstream与ifstream的用法,此处不再獒述,见代码:
看似无问题,但每次从文件中读出的结果总会多出一组数据(最后一组数据会读出两边),找了好久都没有发现,经网上查阅资料总结为以下几点:
1.由于采用的写入语句为“outfile<<name<<" "<<id<<" "<<math<<" "<<eng<<" "<<computer<<endl;“,即每次写完一组数据后,都会向文件中写入一个回车符,所以在读文件的时候,当读到最后一组数据时,读完之后,文件中还有一个回车符没有读出来,此时判断eof()并不为-1,故还会再进行一次读操作;这次读操作实际上并没读到什么,但还有一个输出,输出的为上次读操作的结果,故最后一组数据显示两次。
2.eof()判断的是文件中所有的字符包括回车,只有当文件中什么字符都没有了,才会返回-1,到达文件的末尾。
3.故再使用infile和outfile对文件进行操作时,应该先读再判断(例如,本例中,先读一个name,再进行判断,当遇到最后一个回车符时,会有infile>>name这个操作正好解决了它这样能保证你写的和读的内容是一样的。
4.所以,较好的读文件方式如下
#include<iostream> #include<fstream> using namespace std; int main() { ofstream outfile("student.dat"); char name[8],id[8]; int math,eng,computer; for(int i = 0; i < 3; ++i) { cout<<" input name: "; cin>>name; cout<<" input id: "; cin>>id; cout<<" input math: "; cin>>math; cout<<" input eng: ";cin>>eng; cout<<" input computer: "; cin>>computer; //写文件 outfile<<name<<" "<<id<<" "<<math<<" "<<eng<<" "<<computer<<endl; } 向文件写完之后,再从文件中读取,源码如下:
include<iostream> #include<fstream> using namespace std; int main() { ifstream infile("student.dat"); char name[8],id[8]; int math,eng,computer; int i = 0; char c; while((c=infile.get())!=EOF) { infile>>name>>id>>math>>eng>>computer; cout<<"name: "<<name<<endl; cout<<"id: "<<id<<endl; cout<<"math: "<<math<<endl; cout<<"eng: "<<eng<<endl; cout<<"computer: "<<computer<<endl; } infile.close(); }
看似无问题,但每次从文件中读出的结果总会多出一组数据(最后一组数据会读出两边),找了好久都没有发现,经网上查阅资料总结为以下几点:
1.由于采用的写入语句为“outfile<<name<<" "<<id<<" "<<math<<" "<<eng<<" "<<computer<<endl;“,即每次写完一组数据后,都会向文件中写入一个回车符,所以在读文件的时候,当读到最后一组数据时,读完之后,文件中还有一个回车符没有读出来,此时判断eof()并不为-1,故还会再进行一次读操作;这次读操作实际上并没读到什么,但还有一个输出,输出的为上次读操作的结果,故最后一组数据显示两次。
2.eof()判断的是文件中所有的字符包括回车,只有当文件中什么字符都没有了,才会返回-1,到达文件的末尾。
3.故再使用infile和outfile对文件进行操作时,应该先读再判断(例如,本例中,先读一个name,再进行判断,当遇到最后一个回车符时,会有infile>>name这个操作正好解决了它这样能保证你写的和读的内容是一样的。
4.所以,较好的读文件方式如下
infile>>name; while((c=infile.get())!=EOF) { infile>>id>>math>>eng>>computer; cout<<"name: "<<name<<endl; cout<<"id: "<<id<<endl; cout<<"math: "<<math<<endl; cout<<"eng: "<<eng<<endl; cout<<"computer: "<<computer<<endl; infile>>name; }
相关文章推荐
- 遇到的关于ifstream::eof()的一点小问题
- 转载 - C++ - 关于ifstream/fstream流 判断文件是否结束eof()的问题
- C/C++ ifstream之eof() 对最后字符读双次的问题
- C++ 输入流 cin/ ifstream/ istringstream 及几个相关函数在遇到文件结束符EOF时的行为
- 关于ifstream打开windows文件失败的问题
- CrossApp开发时, 存放在Resource下的文件在android环境下使用assets/..路径 使用C++的文件操作类如(fopen、ifstream等)找不到的问题
- C++文件读写详解(ofstream,ifstream,fstream)
- C++文件读写详解(ofstream,ifstream,fstream)
- C++中关于配置文件的问题
- 关于winodows下编程c++遇到的引用文件路径问题
- C++文件读写详解(ofstream,ifstream,fstream)
- c++关于文件打开目录的问题
- 【转载】C++文件读写详解(ofstream,ifstream,fstream)
- 关于c++问题while(cin>>x)怎么用eof结束
- 关于c/c++ 工程中获取文件路径、设置输出文件路径的问题
- C++ 读写文件方法--fstream,ofstream,ifstream
- C++文件读写详解(ofstream,ifstream,fstream)
- 关于std::fstream以及std::ifstream打开中文路径名失败的问题和解决方法
- C++文件读写详解(ofstream,ifstream,fstream)
- C++fstream,ifstream和outstream读取文件最后一行注意