首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++资料基本操作

2013-07-09 
c++文件基本操作怎么把数据从文件原样取出?#include iostream#include fstreamusing namespace stdin

c++文件基本操作
怎么把数据从文件原样取出?

#include <iostream>
#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 ;
}
C++
[解决办法]
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 ;


}


[解决办法]
引用:
input.eof() 换成 input.good()就正常了。 在检测EOF 的功能上。这两个函数应该是一样能达到效果的啊。为什么用eof()来检测就会出错??

http://blog.csdn.net/zhangxinrun/article/details/5745433 eof()返回true时是读到文件结束符0xFF,而文件结束符是最后一个字符的下一个字符。
while ( !infile.eof())// 所以执行了两次

热点排行