【发布时间】: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()文件? -
如果多次打开文件,则需要关闭多次。
-
我已经把那条线移到外面了,还是不行
-
到哪里去?