c++文件基本操作
怎么把数据从文件原样取出?
#include <iostream>C++
#include <fstream>
using namespace std;
int main ()
{
int age = 20;
char name[10] = "lxr" ;
char filename[20] = "学生信息.txt";
ifstream infile ;
ofstream outfile ;
outfile.open(filename) ;
outfile << name<<age<<endl ;
outfile.close();
infile.open(filename) ;
if ( !infile.is_open())
cout << "open filed\n" ;
while ( !infile.eof())
infile >> name >> age ;
infile.close() ;
cout << name << age <<endl;
return 0 ;
}
[解决办法]
outfile << name<<" "<<age<<endl;
>>操作符与scanf是类似的规则,以空白符为不同输入条目的定界符,因此在输出时要插入一个空格,以便于在输入时>>操作符能够将不同条目分开。
[解决办法]
这两个函数效果不一样。
eof只检测是否到达文件尾
good检测流是否处于正常状态。
如果文件遇到不正确的输入,比如“>> age”时遇到非空白非数字字符,fail被置位,这时eof为false,但good也为false。
出现这种情况(!eof()判断与good()判断不一致),说明在流中有不符合输入格式的数据。如果你已经按我说的改了,我估计是老的数据在干扰,把文件清空一下。
或改一下这条语句:
outfile.open(filename,ios_base::trunc);
不过这样会让每次输出都将以前的结果清空。
[解决办法]
用空格分隔字段。
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
int age = 20;
char name[10] = "lxr" ;
char const* filename = "学生信息.txt";
{
ofstream outfile(filename) ;
outfile << name << ' '<< age<<endl;
}
{
ifstream infile(filename);
while (infile.get(name, 20, ' ') && infile >> age)
cout << name << age <<endl;
}
return 0 ;
}
[解决办法]
http://blog.csdn.net/zhangxinrun/article/details/5745433 eof()返回true时是读到文件结束符0xFF,而文件结束符是最后一个字符的下一个字符。
while ( !infile.eof())// 所以执行了两次