0

So I created a program , when you write " user.create " in the console it will tell you to input a name and a password , after that , the username and the password are being written in the text file " nice.txt " , but every time you start the program , " nice.txt " is cleared , how can I leave text there and read it when I need to ?!

here is the sample code :

#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";
        }
    }
}

basically when you type in " user.access " it should read text from " nice.txt " which is empty because it's cleared every time you execute the .exe

Vlad
  • 3
  • 1
  • Possible duplicate of [How to append text to a text file in C++?](https://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c) – eesiraed May 18 '19 at 20:38

1 Answers1

0

You need to open your file with append mode. When you open to writing it, the default mode is std::ios::out. This mode moves the cursor to the beginning of the file and if you write some text on the file, it will overlay the old data.

You need to use std::ios::app. This mode moves the cursor to the end of the file, avoiding the overlay.

Change:

ofstream out("nice.txt");

to:

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

You can read more about this here.

lucas.exe
  • 119
  • 3