C++ 从现有输入变量到文件的新输入

c++ new input to file from existing input variables

本文关键字:输入 新输入 文件 变量 C++      更新时间:2023-10-16

所以这个问题可能被问过,但对于我的生活,我找不到任何地方。也许我的措辞不正确。如果是这样,请道歉。

所以基本上,我正在向文件写入出租车号码和排名 ID 的列表。当我输入它时,它会正确写入文件,但如果有意义,它会重复相同的输入。

这是我的代码:

void transactionlog(int taxi_number, int rank_id)
{
    int count = 0;
    ofstream myfile;
    myfile.open("transactionlog.txt");
    while (count < 2)
    {
        myfile << "Joined the rank: ";
        myfile << "ntTaxi number: " << taxi_number;
        myfile << "ntRank id: " << rank_id;
        count = count + 1;
    }

}
void main()
{
    node* front = NULL;
    node* back = NULL;
    int choice;
    int taxi_number;
    int rank_id;

    do {
        choice = menu();
        switch (choice)
        {
        case 1:
            cout << "Enter your taxi number: >";
            cin >> taxi_number;
            cout << "Enter your rank id: >";
            cin >> rank_id;
            cout << "n";
            joinRank(front, back, taxi_number);
            transactionlog(taxi_number, rank_id);
        break;

然后这是我得到的输出(在文本文档中重新格式化)

加入行列: 出租车号码: 434 排名 ID: 23

加入行列: 出租车号码: 434 排名 ID: 23

我希望文件中的第二个条目根据我输入的内容具有不同的日期。

对不起,如果这太长了

首先为什么要

使用迭代两次的循环将输入写入文件?

第二:此循环将相同的最后一个输入写入文件两次,并清除之前的内容,只要您使用在写入模式下打开文件而不指定追加模式。

将函数transactionlog更正为:

void transactionlog(int taxi_number, int rank_id)
{
    ofstream myfile("transactionlog.txt", ios::app);
    myfile << "Joined the rank: ";
    myfile << "ntTaxi number: " << taxi_number;
    myfile << "ntRank id: " << rank_id;
    myfile.close(); // to save the content
}