C++如何通过输入输出流重载方法读取文件中的数据,并且将数据保存到类的变量中?
12 25
15 6
62 51
66 56
如何将这些数据保存到类的private成员中 展开
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class haha{
private:
int a[8];
int size;
public:
void input(string filename)
{
ifstream infile(filename.c_str());
int i=0;
int temp=0;
while(infile>>temp)
{
a[i]=temp;
i++;
}
size=i;
}
void show(){
for(int i=0;i<size;i++)
cout<<a[i]<<" ";
}
};
int main()
{
haha xiaojiba;
cout<<"Input filename:"<<endl;
string name;
cin>>name;
xiaojiba.input(name);
xiaojiba.show();
return 0;
}
谢谢你
是重载>
不是文件输入输出流
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class haha{
private:
int a[8];
int size;
public:
void input(string filename)
{
ifstream infile(filename.c_str());
int i=0;
int temp=0;
while(infile>>temp)
{
a[i]=temp;
i++;
}
size=i;
}
void show(){
for(int i=0;i<size;i++)
cout<<a[i]<<" ";
}
friend void operator >>(string name,haha &a)
{
a.input(name);
}
};
int main()
{
haha xiaojiba;
cout<<"Input filename:"<<endl;
string name;
cin>>name;
name>>xiaojiba;
//xiaojiba.input(name);
xiaojiba.show();
return 0;
}
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
/*文件内容格式:
1 1 asd asd 1
2 2 asaad aasd 2
3 3 asaad asad 3
.....
*/
int main()
{
int a,b,c;
char SongName[50];
char Name[50];
memset(SongName,0,50);
memset(Name,0,50);
FILE * fp = fopen("test.dat","r");
if(!fp)
{
printf("file open error\n");
exit(-1);
}
while(fscanf(fp,"%d%d%s%s%d",&a,&b,SongName,Name,&c) != EOF)
{
printf("%d\t%d\t%s\t%s\t%d\n",a,b,SongName,Name,c);
memset(SongName,0,50);
memset(Name,0,50);
}
return 0;
}
自己看看吧! 改改就好 C++ 里也能可以用while(fscanf(fp,"%d%d%s%s%d",&a,&b,SongName,Name,&c) != EOF) 只是后面赋值的时候改为你对象下面对应的属性值!
2013-05-25