当前位置:编程学习 > C/C++ >>

C++ 文件问题

data文件里的东西是
liming 1 200
xiaoqiang 2 300
xiaozhu 3 100
xiaokai 4 600

本来是要执行把100改为500 然后放到data1 就这么简单 可是 为什么后面多了 4 600这个尾巴 帮忙改正下

#include<cstdlib>
#include<conio.h>
#include<fstream>
#include<iostream>
#include<string>
#include <sstream>
using namespace std;


ofstream fout("F:\\data1.txt");
class A
{
private:
string m_name;
int m_index;
int m_count;
public:
A(string name,int index,int count)
{
m_name=name;
m_index=index;
m_count=count;
}
void Modify(int count)//读入cout
{
m_count=count;
}
void Output()
{
cout<<"Name is:"<<m_name<<" ;Index is:"<<m_index<<" ; Count is:"<<m_count<<endl;
}
void Write()
{
fout<<m_name<<" "<<m_index<<" "<<m_count<<endl;
}

};

int main()
{
ifstream fin("F:\\data.txt");

if(!fin)
{
cout<<"Open file error!"<<endl;
return 0;
}
string name;
int index,count;
while(fin)
{
fin>>name;
fin>>index;
fin>>count;
A obj(name,index,count);
obj.Output();
if(count==100)
obj.Modify(500);
cout<<"修改后的结果:"<<endl;
obj.Output();
obj.Write();
}
return 0;
}
答案:
如数文件尾有空格,呵呵

#include "stdafx.h"
#include<iostream>
#include<sstream>
#include<fstream>
#include<string>

using namespace std;
ofstream fout("data_m.txt",ios::app);
class A
{
public:
A(string name,int index,int count)
{
m_name=name;
m_index=index;
m_count=count;
}
void Modify(int count)
{
m_count=count;
}
void Output()
{
cout<<"Name is:"<<m_name<<" ;Index is:"<<m_index<<" ; Count is:"<<m_count<<endl;
}
void Write()
{
fout<<m_name<<" "<<m_index<<" "<<m_count<<endl;
}
private:
string m_name;
int m_index;
int m_count;
};

int _tmain(int argc, _TCHAR* argv[])
{
ifstream fin("data.txt");
string modify_name;
cout<<"请输入要修改的姓名:"<<endl;
cin>>modify_name;
if(!fin)
{
cout<<"Open file error!"<<endl;
return 0;
}
string name;
int index,count;
while(!fin.eof())
{
fin>>name;
fin>>index;
fin>>count;
A obj(name,index,count);
obj.Output();
if(count==100 && name==modify_name)
obj.Modify(500);
cout<<"修改后的结果:"<<endl;
obj.Output();
obj.Write();
}

return 0;
}
修改后的,满足你的要求
while(fin)改成while(!fin.eof())就可以了
如果文件末尾有空行的话就会多读,要去掉空行。

上一个:c++ 手机电话簿
下一个:Visual C++ 6.0

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,