我创建了一个a=[0,1,2,3]
for a[2] in a:
print(a[2])
参赛作品,其中包含class
名称,string
id,int
成绩。然后,我使用程序 P1 以char
模式在文本文件中写入数据。我有另一个程序 P2 ,它在之前的数据之间插入一个新数据。
当我最初使用某些对象创建文本文件时,它显示数据(使用程序P1)。但是,当我插入新数据(使用程序P2)时,属性binary
和id
会出现,但属性grade
会丢失。
name
班级代码:
Scholar
计划#ifndef SCHOLAR_H
#define SCHOLAR_H
#include <iostream>
#include <cstdio>
using namespace std;
class Scholar {
int id;
string name;
char grade;
public:
void read_data() {
cout << "\nEnter ID: ";
cin >> id;
string temp;
getline(cin, temp);
cout << "Enter name: ";
getline(cin, name);
cout << "Enter grade: ";
cin >> grade;
}
void print_data() {
cout << "\nID: " << id << " | Name: " << name << " | Grade: " << grade;
}
int modify_data();
int _id() {
return id;
}
string _name() {
return name;
}
char _grade() {
return grade;
}
};
#endif // SCHOLAR_H
:
P1
当我没有插入任何新数据时输出的初始图像:
计划#include "MyHeaderFiles/Scholar.h"
#include <fstream>
#include <cstdlib>
#include <cctype>
int main() {
system("cls");
Scholar sch;
fstream fs;
fs.open("SchDB.txt", ios::out | ios::in | ios::binary | ios::trunc);
if(!fs) {
cerr << "File not found!";
system("PAUSE");
}
char reply;
do {
sch.read_data();
fs.write((char*) &sch, sizeof(sch));
cout << "Do you want to add another scholar (y/n) : ";
cin >> reply;
} while(tolower(reply) == 'y');
fs.seekg(0);
cout << "\nFile content\n------------" << endl;
while(!fs.eof()) {
fs.read((char*) &sch, sizeof(sch));
if(fs.eof()) break;
sch.print_data();
}
fs.close();
cout << endl;
return 0;
}
:
P2
我使用程序#include "MyHeaderFiles/Scholar.h"
#include <fstream>
#include <cstdlib>
int main() {
system("cls");
Scholar sch;
Scholar newSch;
ofstream fout;
ifstream fin;
fout.open("Temp.txt", ios::out | ios::binary);
fin.open("SchDB.txt", ios::in | ios::binary);
char last = 'y';
int pos;
cout << "\nYou have to enter data of a new student." << endl;
newSch.read_data();
fin.seekg(0);
cout << "\nFile content\n------------" << endl;
while(!fin.eof()) {
pos = fin.tellg();
fin.read((char*) &sch, sizeof(sch));
if(sch._id() > newSch._id()) {
fout.write((char*) &newSch, sizeof(newSch));
last = 'n';
break;
} else {
fout.write((char*) &sch, sizeof(sch));
}
}
if(last == 'y') {
fout.write((char*) &newSch, sizeof(newSch));
} else if(!fin.eof()) {
fin.seekg(pos);
while(!fin.eof()) {
fin.read((char*) &sch, sizeof(sch));
if(fin.eof()) break;
fout.write((char*) &sch, sizeof(sch));
}
}
fin.close();
fout.close();
remove("SchDB.txt");
rename("Temp.txt", "SchDB.txt");
fin.open("SchDB.txt", ios::in | ios::binary);
fin.seekg(0);
while(!fin.eof()) {
fin.read((char*) &sch, sizeof(sch));
if(fin.eof()) break;
sch.print_data();
}
fin.close();
cout << endl;
return 0;
}
插入新数据时的后一张图片:
我正在使用Code :: Blocks IDE和GNU GCC Compiler。
有人可以解释一下为什么字符串不会出现吗?