c++ - 如何将文本保留在文件中?
问题描述
所以我创建了一个程序,当你在控制台写“user.create”时它会告诉你输入一个名字和一个密码,然后用户名和密码被写入文本文件“nice.txt”中,但是每次启动程序时,“nice.txt”都会被清除,我怎样才能将文本留在那里并在需要时阅读?!
这是示例代码:
#include <iostream>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file_to_create;
file_to_create.open("nice.txt");
ifstream read("nice.txt");
ofstream out("nice.txt");
string input = " ";
while (1) {
cin >> input;
if (input == "app.exit")
return 0;
else if (input == "user.create") {
string name, password;
cout << "create user->\n";
cout << "name:";
cin >> name;
cout << "password:";
cin >> password;
out << name << '\n' << password << '\n';
cout << "user created.\n";
} else if (input == "user.access") {
string name, password;
cout << "access user->\n";
cout << "name:";
cin >> name;
cout << "password:";
cin >> password;
string look_name, look_password;
bool found = 0;
while (read >> look_name >> look_password) {
if (look_name == name && look_password == password) {
cout << "user " << look_name << " is now connected.\n";
found = 1;
}
}
if (!found)cout << "user not found.\n";
}
}
}
基本上当您输入“user.access”时,它应该从“nice.txt”读取文本,因为每次执行 .exe 时它都会被清除
解决方案
您需要使用append mode
. 当您打开编写它时,默认模式是std::ios::out
. 此模式将光标移动到文件的开头,如果您在文件上写入一些文本,它将覆盖旧数据。
你需要使用std::ios::app
. 此模式将光标移动到文件末尾,避免覆盖。
改变:
ofstream out("nice.txt");
到:
ofstream out("nice.txt", std::ios::app);
您可以在此处阅读有关此内容的更多信息。
推荐阅读
- fullcalendar - jquery全日历自定义滚动条
- python - 如何跳过python列表中的错误链接
- java - 将数据与 OneToMany 关系合并
- python - Django对子查询进行注释
- reactjs - 反应框架和支持框架有什么区别
- svn - 如何使用 Groovy 仅打印 SVN 中更改的目录?
- vue.js - 过渡组的孩子必须有钥匙……但他们有钥匙
- html - href 网页调用自身时的奇怪行为
- dialogflow-es - Dialogflow 在收到 Telegram bot 的请求后如何选择语言?
- python - Seaborn 根据列更改点大小(如色调)