打印

关于文件读写

[复制链接]
1304|1
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
sinadz|  楼主 | 2012-4-13 18:17 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
#include <iostream>#include <fstream>
#include
<vector>
#include
<string>
#include
<iostream>
using
namespace std;
class CPeople  
{
public:
   
void showinformation();
    CPeople(
string name,int age);
   
void getinformation();
private:
   
int m_age;
   
string m_name;
};

void CPeople::getinformation()
{
    cout
<<"enter name: ";
    cin
>>m_name;
    cout
<<"enter age: ";
    cin
>>m_age;
}

CPeople::CPeople(
string name, int age)
{
    m_name
= name;
    m_age
= age;
}

void CPeople::showinformation(){    cout <<"name: "
<<m_name;
    cout
<<"    age: "
<<m_age <<endl;
}

int main()
{
    ifstream infile;
    ofstream outfile;
   
string choice;
    vector
<CPeople> vpeople;
    CPeople peo(
"zhangsan",20);
//     outfile.open("people.txt",ios_base::out|ios_base::binary);
//     do
//     {
//         peo.getinformation();
//         vpeople.push_back(peo);
//         outfile.write(reinterpret_cast<char *>(&peo),sizeof(peo));
//         cout <<"continue?[yes/no]: ";
//         cin >>choice;
//         cin.sync();
//     } while (choice[0] != 'n');
//     outfile.close();
//     for (vector<CPeople>::size_type ix = 0; ix < vpeople.size(); ++ix)
//     {
//         vpeople[ix].showinformation();
//     }
//不注释以上代码 程序可以正确执行  当注释时  在文件中读时就出错了
    infile.open("people.txt",ios_base::in|ios_base::binary);
   
while (infile.peek()!=EOF)
    {
        infile.read(reinterpret_cast
<char
*>(&peo),sizeof(peo));
        peo.showinformation();
    }
    infile.close();
   
return
0;
}

相关帖子

沙发
dfsa| | 2012-4-13 18:35 | 只看该作者
infile.open("people.txt",ios_base::in|ios_base::binary);
  if (infile.eof())//在这儿加个判断就好了
  {
    cout << "file is empty."<<endl;
    return 0;
  }
  while (infile.peek()!=EOF)

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

304

主题

2313

帖子

0

粉丝