0
我已經編寫了一個代碼,用於將學生信息存儲到二進制文件中,並根據需要獲取信息。但我沒有得到所需的輸出。當我試圖從student.bin文件中讀取學生信息時,名稱字段始終顯示NULL,並且滾動字段是最後輸入的滾動編號。這裏有什麼問題?C++中的二進制文件I/O
#include <bits/stdc++.h>
using namespace std;
class student{
public:
string name;
int roll;
};
int main(){
fstream file("student.bin", ios::in | ios::out | ios::binary);
int written = 0;
while(1){
int choice;
student a;
int i;
cout << "0. Exit\n1. Write\n2. Read\nEnter Choice : ";
cin >> choice;
switch(choice){
case 1:
cout << "Enter name & roll : ";
cin >> a.name >> a.roll;
cout << "You entered " << a.name << " " << a.roll << endl;
cout << "Enter the index : ";
cin >> i;
if(i > written){
cout << "This index doesnt exist !" << endl;
break;
}
file.seekp(i * sizeof(student), ios::beg);
file.write((char*) &a, sizeof(student));
written++;
break;
case 2:
cout << "Enter index : ";
cin >> i;
file.seekg(i * sizeof(student), ios::beg);
file.read((char*) &a, sizeof(student));
cout << "Name : " << a.name << " Roll : " << a.roll << endl;
break;
case 0:
exit(0);
default:
cout << "Wrong Choice !" << endl;
break;
}
}
file.close();
}
我想保存'std :: string',它可能使用內部指針來保存文件並不好。 – MikeCAT
'#include'人們在哪裏得到這個想法? –
[如何寫入std :: string到文件?](http://stackoverflow.com/questions/15388041/how-to-write-stdstring-to-file)可能的重複 – MikeCAT