【问题标题】:How to save all data in the file? C++如何保存文件中的所有数据? C++
【发布时间】:2019-10-15 18:06:49
【问题描述】:

我有一个问题,我想在文本文件中保存所有 ID 号,但它只保存用户输入的最后一个 ID 号。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{

    string line;
    int idnum;
    ofstream IdData ("data.txt");

    cout<<" Enter your ID number: "<<endl;
    cin>>idnum;

    if(IdData.is_open())
    {
        IdData<< "ID number of voter is: ";
        IdData << idnum << endl;
        IdData.close();
    }
    else 
        cout<<" Unable to open file";


    ifstream Data ("data.txt");

    if(Data.is_open())
    {
        while (getline (Data, line))
        {
            cout<< line << endl;
        }

        Data.close();
    }
    else
        cout<<" Unable to open file";
}

【问题讨论】:

  • 当你说“最后一个”身份证号码时,你是什么意思?您只需要一个 ID 号!
  • 是的,但是在文本文件中我想查看不同用户输入的所有 ID 号
  • 顺便说一句,如果IdData 无法打开,您的程序会在打印消息后继续。您可能想在打印消息后使用return EXIT_FAILURE;

标签: c++ fstream ifstream ofstream


【解决方案1】:

您只要求用户提供 1 个 ID,然后您将 用包含该 1 个 ID 的新文件覆盖现有文件。

std::ofstream 会破坏现有文件的内容,除非您明确要求它不要这样做。因此,对于您尝试执行的操作,要将新 ID 追加到现有文件的末尾,您需要在打开 std::ofstream 时包含 appate 标志(见C++ Filehandling: Difference between ios::app and ios::ate?),例如:

ofstream IdData ("data.txt", ios::app);

或者:

ofstream IdData ("data.txt", ios::ate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多