C++,在用户确认后继续向文件添加记录

C++, Keep Adding Records To a File besd on User confirmation

本文关键字:文件 添加 加记录 继续 用户 确认 C++      更新时间:2023-10-16

下面的代码能够一次将单个学生信息发送到一个文件中。如何在不退出并重新打开程序的情况下修改为一个接一个地发送更多记录。我是新手。请帮忙。

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <windows.h>
#include <sstream>
#include <algorithm>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <iomanip>
#include <dos.h>
using namespace std;
string userName;
string passWord;
string selection;
int option;
struct patientinfo {
    string PatientFname;
    string PatientLname;
    int Age;
    int ContactNo;
    string TreatmentType;
    string AppDate;
    string AppTime;
    int eReciptId;
};
int num;
patientinfo emp[50];
void makeBooking()
{
ofstream outputFile;
outputFile.open("smt.bin", std::ofstream::in | std::ofstream::out | std::ofstream::app);
int i=num;
num+=1;
cout<< endl << endl << endl << endl << endl << endl 
<< setw(30)<<"First Name       : ";
cin>>emp[i].PatientFname;
outputFile <<emp[i].PatientFname <<",";
cout<< setw(30)<<"Last Name        : ";
cin>>emp[i].PatientLname;
outputFile <<emp[i].PatientLname <<",";
cout<< setw(30)<<"Age        : ";
cin>>emp[i].Age;
outputFile <<emp[i].Age <<",";
}

int main ()
{
    makeBooking();
    return 0;   
}

考虑到您有50名学生想要向他们发送信息,您应该调用makeBooking函数50次。所以在中更改主菜单

int main ()
{
    for (int i = 0; i < 50; i++) {
        makeBooking();
    }
    return 0;   
}

应该做到这一点。然而,一个更优雅的解决方案是将索引i作为函数中的参数发送。所以代码是:

patientinfo emp[50];
void makeBooking(int i)
{
ofstream outputFile;
outputFile.open("smt.bin", std::ofstream::in | std::ofstream::out | std::ofstream::app);
// int i=num; you don't need these anymore
// num+=1;
cout<< endl << endl << endl << endl << endl << endl 
<< setw(30)<<"First Name       : ";
cin>>emp[i].PatientFname;
outputFile <<emp[i].PatientFname <<",";
cout<< setw(30)<<"Last Name        : ";
cin>>emp[i].PatientLname;
outputFile <<emp[i].PatientLname <<",";
cout<< setw(30)<<"Age        : ";
cin>>emp[i].Age;
outputFile <<emp[i].Age <<",";
}

int main ()
{
    char response;
    for (int i = 0; i < 50;) {
        cout << "Do you want to add another person?";
        cin >> response;
        if (response == 'y')
             makeBooking(i++);
        else if (respinse == 'n')
             break;
        else 
             cout << "Undefined response";
    }
    return 0;   
}