【问题标题】:How to add multiple lines to a file in C++?如何在 C++ 中向文件中添加多行?
【发布时间】:2020-08-15 06:37:21
【问题描述】:

我是 C++ 新手,在控制台上写了一个小待办事项列表。 我只能在文本文件中添加一行,但是当我尝试添加更多时,它不会出现在我的文本文件中。

请看看我做错了什么

//output-file stream
    ofstream file;
    file.open("output.txt", std::ios_base::app); //append

    bool isRunning = true;

    while (isRunning) {
        cout << "Please select an action:" << endl;
        cout << "add - adding tasks to the list" << endl;
        cout << "del - deleting tasks to the list" << endl;
        cout << "list - show the list" << endl;
        cout << "x - to exit program" << endl;

        string input;
        cin >> input; 
        string addedTask;

        if (input == "add") {
            cout << "Please enter a task you like to add: " << endl;
            cin.ignore();
            if (std::getline(std::cin, addedTask)) {
                file << addedTask << "\n";
            }
            else {
                cout << "Failed to read line" << endl;
            }
        }

为什么我只能添加一个字符串行?我仍然无法找出问题所在,还是我遗漏了什么?

【问题讨论】:

  • 为什么要反复.open()文件?
  • 如果多次打开文件,则需要关闭多次。
  • 我已经把那条线移到外面了,还是不行
  • 到哪里去?

标签: c++ string file stream


【解决方案1】:

您是否尝试更换您的

file << addedTask << "\n";

file << addedTask << endl;

我认为它应该有效(对我来说它有效)

【讨论】:

  • 不,这只会强制立即刷新。它不会影响最终在文件中结束的数据。虽然如果 OP 试图在运行中观察文件,这可能是相关的,但没有说明。通常,您需要'\n' 而不是endl
  • 当主函数终止时,ofstream 文件 close() 函数被调用,该函数刷新任何剩余的要写入文件的字符串。所以endl; 不应该修复它。我们需要他的完整代码
猜你喜欢
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 2013-04-28
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
  • 2010-10-04
  • 2010-10-10
相关资源
最近更新 更多