【问题标题】:c++ new input to file from existing input variablesc ++从现有输入变量到文件的新输入
【发布时间】:2017-01-13 17:10:48
【问题描述】:

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

所以基本上,我正在将出租车号码和等级 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 << "\n\tTaxi number: " << taxi_number;
        myfile << "\n\tRank 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 排名编号:23

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

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

对不起,如果这有点啰嗦

【问题讨论】:

  • 对于此类本地化问题,很少有重复的。再想想你的程序是怎么回事,也许一步一步地完成它。你会发现为什么有重复的条目,然后你可以弄清楚如何添加不同的数据。
  • 我认为你需要在这里做一些rubber duck debugging
  • 您应该遍历您应该在joinRank 中构建的列表并打印其条目。 (您似乎认为第二个myfile &lt;&lt; "\n\tRank id: " &lt;&lt; rank_id 应该与第一个myfile &lt;&lt; "\n\tRank id: " &lt;&lt; rank_id 产生不同的结果。)
  • 你在函数中写入了最后一个输入两次。所以删除循环。事实上你必须在 alpending 模式下打开文件 'ios::app'

标签: c++ file output


【解决方案1】:

首先为什么要使用循环两次将输入写入文件?

second:此循环将相同的最后输入两次写入文件并清除以前的内容,只要您使用以写入模式打开文件而不指定附加模式。

将函数transactionlog更正为:

void transactionlog(int taxi_number, int rank_id)
{

    ofstream myfile("transactionlog.txt", ios::app);

    myfile << "Joined the rank: ";
    myfile << "\n\tTaxi number: " << taxi_number;
    myfile << "\n\tRank id: " << rank_id;

    myfile.close(); // to save the content
}

【讨论】:

  • 那是我尝试某事的时候。并感谢您的帮助。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 2019-01-10
  • 2020-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多