C++ 怎样从TXT文件中读取数据存到结构体数组中

来源:百度知道 编辑:UC知道 时间:2024/07/08 20:56:12
rt

首席需要用到fstream头文件,然后用ifstream就可以了。
我给LZ写一个例子,lz看一下就明白了:

strcut stockType
{
string personAddress;
string personCity;
string personState;
int personZIP;
};

void addressType :: getData()
{
ifstream infile;

int index;

string inputFile;

stockType addressTypeList[NO_OF_PERSON];

cout<<"Enter the file path: ";
cin>>inputFile; //输入txt文件路径
cout<<endl;

infile(inputFile.c_str()); //infile按照指定路径读取txt文件

for(index = 0; index < NO_OF_PERSON; index++)//读取txt文件至struct
{
infile>>addressTypeList[index].personAddress;
infile>>addressTypeList[index].personCity;
infile>>addressTypeList[index].personState;
infile>>addressTypeList[index].personZIP;
}
}

直接给你个参考:(你的文件必须在当前的目录下,名为test.txt)#include<iostream>#include<fstream>usingnamespacestd;structTEST{charnam