Reading line to line of file .txt

2

I am trying to read a .txt file using C ++, in which the user enters (in this case a "user" and a "pass") two data, and when you compare them, if both, print on the screen a type "Login correct". The code is as follows:

#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main(){
    ifstream archivo("user.txt");

    //Obtencion de datos
    cout << "Usuario: ";
    char user[25];
    cin.getline(user,25,'\n');

    cout << "Pass: ";
    char pass[25];
    cin.getline(pass,25,'\n');

    //Creacion de la linea a buscar
    char busqueda[100];
    strcpy(busqueda, user);
    strcat(busqueda, " ");
    strcat(busqueda, pass);

    char linea[100];
    while(!archivo.eof() || busqueda != linea){
        for(int i = 0; i!=archivo.eof(); i++){
            archivo.getline(linea, 100);
        }
    }

    cout << endl << endl << "LOGIN CORRECTO." << endl << linea; 

    return 0;
}

The problem is that once you enter the two data, it stays in an infinite loop in which it does nothing. You can be giving intro all the time that does not come out of there ...

Doing more tests, I have reached the following code. The only thing is that it only compares with the first line of the file.

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

struct registro{
    string name;
    string second;
    string street;
    string user;
    string pass;
} usuario;

void registroUsuario(){
    ofstream archivo("registro.txt");
    archivo << "----------------------" << endl;
    archivo << "Nombre: " << usuario.name << endl;
    archivo << "Apellido: " << usuario.second << endl;
    archivo << "Direccion: " << usuario.street << endl;
    archivo << "Usuario: " << usuario.user << endl;
    archivo << "Password: " << usuario.pass << endl;
    archivo.close();
}

void registroLogin(){
    ofstream archivo("usuarios.txt");
    archivo << usuario.user;
    archivo << " ";
    archivo << usuario.pass;
    archivo << "\n";
    archivo.close();
}

bool login(string usuario, string password){
    ifstream archivo("usuarios.txt");
    string busqueda = usuario + " " + password;
    string linea;
    while(!archivo.eof()){
        getline(archivo, linea);
        if(linea == busqueda){
            return true;
        }
        else{
            return false;
        }
    }
}

int main(){
    menu:
        cout << "\t\t\t *** Base de datos ***" << endl << endl;
        cout << "1. Registro de usuario" << endl;
        cout << "2. Login" << endl;
        cout << "0. Salir" << endl << endl;

        cout << "Escoge una opcion: ";
        int option;
        cin >> option;
        cin.ignore();
        cout << endl << endl;
        system("pause");

        switch(option){
            case 1:{
                system("cls");
                cout << "Nombre: ";
                getline(cin, usuario.name);
                cout << endl << "Apellido: ";
                getline(cin, usuario.second);
                cout << endl << "Direccion: ";
                getline(cin, usuario.street);
                cout << endl << endl << "Nombre de usuario: ";
                getline(cin, usuario.user);
                cout << endl << "Password: ";
                getline(cin, usuario.pass);

                registroUsuario();
                registroLogin();
                cout << endl << endl;
                system("pause");
                goto menu;
                break;
            }
            case 2:{
                system("cls");
                cout << "Usuario: ";
                getline(cin, usuario.user);
                cout << endl << "Password: ";
                getline(cin, usuario.pass);

                if(login(usuario.user, usuario.pass) == true){
                    goto login;
                }
                else{
                    cout << endl << endl << "Login incorrecto.";
                    goto menu;
                }
                break;
            }
        }
    login:
        cout << endl << endl << endl << "LOGIN CORRECTO";


    return 0;
}
    
asked by Jogofus 04.04.2017 в 22:12
source

1 answer

0

It is not necessary to reinvent the wheel for this, you can store your objects of type registro in a std::map indexed by name:

struct registro{
    std::string name;
    std::string second;
    std::string street;
    std::string user;
    std::string pass;
};

std::map<std::string, registro> registros;

I advise you to create a function that saves records in file:

void guardar_registro(const registro &un_registro)
{
    // Abrir el archivo para agregar datos al final del mismo
    if (std::ofstream user{"user.txt", std::ios_base::app})
    {
        user << un_registro.name   << '\n'
             << un_registro.second << '\n'
             << un_registro.street << '\n'
             << un_registro.user   << '\n'
             << un_registro.pass   << '\n';
    }
}

And one that reads the file and fills in the map of registros :

std::map<std::string, registro> leer_registros()
{
    std::map<std::string, registro> resultado;

    if (std::ifstream user{"user.txt"})
    {
        registro nuevo_registro{};

        while (
               std::getline(user, nuevo_registro.name)   &&
               std::getline(user, nuevo_registro.second) &&
               std::getline(user, nuevo_registro.street) &&
               std::getline(user, nuevo_registro.user)   &&
               std::getline(user, nuevo_registro.pass)) {
            resultado.insert(nuevo_registro.user, nuevo_registro);
        }
    }

    return resultado;
}

In this way, it is easy to verify if a user exists and your password matches, delegating to the % function std::map::find of map :

int main(){
    std::map<std::string, registro> registros = leer_registros();
    bool login = false;

    while (!login) {
        std::cout << "Usuario: ";
        std::string u;
        std::getline(std::cin, u);

        std::cout << "\nPassword: ";
        std::string p;
        std::getline(std::cin, p);

        auto usuario_existe = registros.find(u);
        if ( (login = (usuario_existe != registros.end())) )
        {
            if ( (login = (usuario_existe->second.pass == p)) )
            {
                std::cout << "\n\n\nLOGIN CORRECTO";
            }
            else
            {
                std::cout << "\n\nLogin incorrecto.";
            }
        }
    }

    return 0;
}

The std::getline function reads full lines and returns the flow (" stream ") that did the reading, this flow has a Boolean conversion operator that, if the flow is in the correct state, will return true (more details here ).

    
answered by 13.06.2017 / 11:00
source