第一个图:创建一个文件:
第二个图:读取文件
第三个图:运行结果
并没有被成功读取,为什么啊?还有那个while循环是做什么用的?接下来为源码:
//创建文件
//创建文件
#include <fstream>
#include <iostream>
using namespace std;
struct student
{
char name[20];
char sex;
unsigned long birthday;
float height;
float weight;
};
int main()
{
student room[4] = {
{"Lixin", 'M', 19840318, 1.82, 65.0},
{"Zhangmeng", 'M', 19840918, 1.75, 58.0},
{"Helei", 'M', 19841209, 1.83, 67.1},
{"Geyujian", 'M', 19840101, 1.70, 59.0}};
ofstream fout("Student.txt");
if (!fout)
{
cout << "文件夹打开失败!";
return 0;
}
for (int i = 0; i < 4; i++)
fout << room[i].name
<< room[i].sex
<< room[i].birthday
<< room[i].weight << endl;
fout.close();
return 0;
}
//调用文件
#include <fstream>
#include <iostream>
using namespace std;
struct student
{
char name[20];
char sex;
unsigned long birthday;
float height;
float weight;
};
int main()
{
ifstream fin("Student.txt");
if (!fin)
{
cout << "文件夹打开失败!";
return 1;
}
cout << "姓名\t性别\t生日\t身高\t体重" << endl;
student S;
while (fin >> S.name >> S.sex >> S.birthday >> S.height >> S.weight)
{
cout << S.name << "\t"
<< S.sex << "\t"
<< S.birthday << "\t"
<< S.height << "\t"
<< S.weight << "\t";
}
fin.close();
system("pause");
return 0;
}