首页 > 解决方案 > 如何将文本保留在文件中?

问题描述

所以我创建了一个程序,当你在控制台写“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 时它都会被清除

标签: c++

解决方案


您需要使用append mode. 当您打开编写它时,默认模式是std::ios::out. 此模式将光标移动到文件的开头,如果您在文件上写入一些文本,它将覆盖旧数据。

你需要使用std::ios::app. 此模式将光标移动到文件末尾,避免覆盖。

改变:

ofstream out("nice.txt");

到:

ofstream out("nice.txt", std::ios::app);

您可以在此处阅读有关此内容的更多信息。


推荐阅读