C++无法将学生信息以正确文本格式写入文件的技术求助
问题描述
编写的C++学生信息管理程序,期望将学生的姓名(name)、学号(roll)、百分比(per)以可读的文本格式写入student.txt文件,但当前代码使用f.write()写入整个student对象,导致文件内容为二进制格式(显示乱码)。
原代码如下:
#include<iostream> #include<fstream> using namespace std; class student { string name; int roll; float per; public: void put() { cout << "Name: " << name << endl; cout << "Roll no.: " << roll << endl; cout << "Percentage: " << per << endl; cout << endl; } void get() { cout << "Enter your name: "; cin >> name; cout << "Enter your roll no.: "; cin >> roll; cout << "Enter your percentage: "; cin >> per; cout << endl; } }; int main() { student s; fstream f; int ch; while(1) { cout<<"\n-------------------MENU-------------------\n"; cout<<"1.Add Record\n"; cout<<"2.Search\n"; cout<<"3.Delete\n"; cout<<"4.Modify\n"; cout<<"5.Display File\n"; cout<<"6.QUIT\n"; cout << "\nEnter your choice: "; cin>>ch; switch(ch) { case 1: f.open("student.txt", ios::app); s.get(); f.write((char*)&s, sizeof(s)); f.close(); break; case 5: f.open("student.txt", ios::in); while (f.eof() != 0) { f.read((char*)&s, sizeof(s)); s.put(); } f.close(); break; case 6: cout << "Quiting\n"; return -1; default: cout << "Invalid input"; } } return 0; }
修改方案
要实现可读文本格式的写入和读取,需要替换二进制读写的f.write()和f.read(),改用文本流操作(类似cout和cin的方式),同时为student类添加文本读写的成员函数以保证封装性。
具体修改点:
- 新增
writeToFile成员函数,将学生信息按文本格式写入文件流 - 新增
readFromFile成员函数,从文本文件流读取数据并初始化对象 - 修改主函数中添加记录和显示文件的逻辑,替换二进制读写为文本读写
- 修复文件读取时的结束判断逻辑,避免重复输出最后一条记录
修改后的代码:
#include<iostream> #include<fstream> #include<string> using namespace std; class student { string name; int roll; float per; public: void put() { cout << "Name: " << name << endl; cout << "Roll no.: " << roll << endl; cout << "Percentage: " << per << endl; cout << endl; } void get() { cout << "Enter your name: "; cin >> name; cout << "Enter your roll no.: "; cin >> roll; cout << "Enter your percentage: "; cin >> per; cout << endl; } // 将学生信息以文本格式写入文件流 void writeToFile(ofstream& out) const { out << name << " " << roll << " " << per << endl; } // 从文件流读取文本格式的学生信息,读取失败返回false bool readFromFile(ifstream& in) { return in >> name >> roll >> per; } }; int main() { student s; int ch; while(1) { cout<<"\n-------------------MENU-------------------\n"; cout<<"1.Add Record\n"; cout<<"2.Search\n"; cout<<"3.Delete\n"; cout<<"4.Modify\n"; cout<<"5.Display File\n"; cout<<"6.QUIT\n"; cout << "\nEnter your choice: "; cin>>ch; switch(ch) { case 1: ofstream outFile("student.txt", ios::app); s.get(); s.writeToFile(outFile); outFile.close(); break; case 5: ifstream inFile("student.txt"); while (s.readFromFile(inFile)) { s.put(); } inFile.close(); break; case 6: cout << "Quiting\n"; return 0; default: cout << "Invalid input\n"; } } return 0; }
说明
- 修改后
student.txt中每一行对应一个学生的信息,格式为姓名 学号 百分比,例如Alice 101 92.5,完全可读 readFromFile通过返回值判断读取状态,解决了原代码中while(f.eof() !=0)导致的重复读取问题- 使用
ofstream和ifstream分别处理写入和读取,逻辑更清晰
内容的提问来源于stack exchange,提问作者Akshay
相关产品推荐
相关产品推荐

