第一个图:创建一个文件:
第二个图:读取文件
第三个图:运行结果
并没有被成功读取,为什么啊?还有那个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;
}
首先,你存到文件里面去了,所有的类型都变成string了。所以读的时候再存需要转换一下 其次,你存的时候都没存身高。 帮你改了一下,供你测试
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
struct student
{
char name[20];
char sex;
unsigned long birthday;
float height;
float weight;
};
void newFile() {
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;
}
for (int i = 0; i < 4; i++)
fout << room[i].name << "\t"
<< room[i].sex << "\t"
<< room[i].birthday << "\t"
<< room[i].height << "\t"
<< room[i].weight << endl;
fout.close();
}
void openFile() {
ifstream fin("Student.txt");
if (!fin)
{
cout << "文件夹打开失败!";
return;
}
cout << "姓名\t性别\t生日\t身高\t体重" << endl;
student S;
string tmp;
while (getline(fin, tmp))
{
cout << tmp << endl;
// cout << S.name << "\t"
// << S.sex << "\t"
// << S.birthday << "\t"
// << S.height << "\t"
// << S.weight << "\t";
}
fin.close();
}
int main() {
newFile();
openFile();
return 0;
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。