我正在编写一个基本的待办事项应用程序来读取文本文件和向文本文件写入注释。我的代码的问题是它不会在我的文件中读取或写入空格,就像我添加一个像“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;
}
}
}
}
您仅在
writer
分支中使用//Adding a ToDo
,在那里声明它(正确的类型std::ofstream
),打开文件进行附加(谷歌std::ios_base::app
),附加smth并关闭。在您的代码中,writer
可以在关闭后使用,这会导致异常或“软”错误(设置errno
),不确定。