在 Fstream C++ 中读写文件

问题描述 投票:0回答:1

我正在编写一个基本的待办事项应用程序来读取文本文件和向文本文件写入注释。我的代码的问题是它不会在我的文件中读取或写入空格,就像我添加一个像“hello world”这样的待办事项,只有 hello 被写入文件

这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    bool running = true;
    string input;
    string output;

    while (running) {
        fstream writer("todo.txt");
        // Getiing The Input Of The User
        cout << "What would you like to do (type 'help' for help)  \n";
        cin >> input;

        // The Help Function
        if (input == "help") {
            cout << "  Adding a todo(add) \n  Removing a todo(remove) \n  Viewing Todos(view)  \n  Killing the program(exit0)\n";
        }
        //For Closing The App
        else if (input == "exit0") {
            writer.close();
            return 0;
        }
        //Adding a ToDo
        else if (input == "add") {
            writer.seekg(0, fstream::end);
            cout << "What is your todo/note for today \n";
            cin >> input;
            writer << input << endl;
            writer.close();
        }
        else if (input == "view") {
            while (getline(writer, output)) {
                // Output the text from the file
                cout << endl << output;
            }
        }
    }
}
c++ file iostream
1个回答
0
投票

您仅在

writer
分支中使用
//Adding a ToDo
,在那里声明它(正确的类型
std::ofstream
),打开文件进行附加(谷歌
std::ios_base::app
),附加smth并关闭。在您的代码中,
writer
可以在关闭后使用,这会导致异常或“软”错误(设置
errno
),不确定。

© www.soinside.com 2019 - 2024. All rights reserved.