如何在不破坏旧数据的情况下向文件添加新数据?数据包含名称和年龄字段。这是我的代码:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
char data[100];
ofstream outfile;
outfile.open("afile.txt");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("afile.txt");
cout << "Reading from the file" << endl;
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
infile.close();
return 0;
}