C++怎么从文本文件读取内容到结构数组呢
4SamStone2000FreidaFlass100500TammyTubbs5000RicRaptor55000第一个行是人数然后人名钱数。。。我只会把人数读到数组中...
4
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Ric Raptor
55000
第一个行是人数 然后 人名 钱数 。。。
我只会把人数读到数组中
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct information
{
string name;
double donation;
};
int main()
{
cout << "Enter your name open file : ";
string fileName;
cin >> fileName;
ifstream inFile;
inFile.open(fileName);
if(!inFile.is_open())
{
cout << "没有这个文件:" << fileName << endl;
exit(EXIT_FAILURE);
}
int numberOfPeople;
inFile >> numberOfPeople;
information* Pin= new information[numberOfPeople];
return 0;
}
坐等好人。。 展开
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Ric Raptor
55000
第一个行是人数 然后 人名 钱数 。。。
我只会把人数读到数组中
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct information
{
string name;
double donation;
};
int main()
{
cout << "Enter your name open file : ";
string fileName;
cin >> fileName;
ifstream inFile;
inFile.open(fileName);
if(!inFile.is_open())
{
cout << "没有这个文件:" << fileName << endl;
exit(EXIT_FAILURE);
}
int numberOfPeople;
inFile >> numberOfPeople;
information* Pin= new information[numberOfPeople];
return 0;
}
坐等好人。。 展开
2个回答
展开全部
好人是我. 给你写了.
用了动态数据 vector , 从代码你应该能看懂用法.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
struct information
{
string name;
double donation;
};
void main()
{
fstream ifs("list.txt");
if (!ifs.is_open())
{
cout << "open file error" << endl;
return;
}
string line;
information info;
int step = 0;//行数
vector<information> vInFo;
while(getline(ifs,line))
{
if (step++%2 == 0)
{
info.name = line;
}
else
{
info.donation = atof(line.c_str());
vInFo.push_back(info);
}
}
for (int i=0;i<vInFo.size();i++)
{
cout << vInFo[i].name << ":" << vInFo[i].donation << endl;
}
system("pause");
}
附: list.txt
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Ric Raptor
55000
用了动态数据 vector , 从代码你应该能看懂用法.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
struct information
{
string name;
double donation;
};
void main()
{
fstream ifs("list.txt");
if (!ifs.is_open())
{
cout << "open file error" << endl;
return;
}
string line;
information info;
int step = 0;//行数
vector<information> vInFo;
while(getline(ifs,line))
{
if (step++%2 == 0)
{
info.name = line;
}
else
{
info.donation = atof(line.c_str());
vInFo.push_back(info);
}
}
for (int i=0;i<vInFo.size();i++)
{
cout << vInFo[i].name << ":" << vInFo[i].donation << endl;
}
system("pause");
}
附: list.txt
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Ric Raptor
55000
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询