1

Всем привет, как мне сделать,чтобы при чтении из файла читало не только первую запись, а всё, что есть в файле? В данном случаи мне нужно это для авторизации, в файле две записи,и должна быть возможность авторизоваться под любой из них,но сейчас это возможно только под первой записью в файле

struct Account  {
    string login;
    string password;
    int role; //0-студент ,1 -админ

};

void GlavnoeMenu();
void login(Account *arr_of_accounts, int &number_of_accounts);
void MenuAccounts();
void writeFileAccounts(Account *arr_of_accounts, int number_of_accounts); //запись в файл (если что-то было в файле,данные исх. будут удалены)
void writeEndFileAccounts(Account new_account );
void readFileAccounts(Account *arr_of_accounts, int &number_of_accounts); //чтение из файла в массив
void showAccounts(Account *arr_of_accounts, int number_of_accounts);
void addAccount(Account *arr_of_accounts, int &number_of_accounts);
void delAccount(Account *arr_of_accounts, int &number_of_accounts);
void updateAccount(Account *arr_of_accounts, int number_of_accounts);

const int SIZE_ARR_OF_ACCOUNTS = 100; //константа для размера нашего массива в  100 элементов
const string FILE_OF_ACCOUNTS = "Accounts.txt";// ПУТЬ К ФАЙЛУ
void main()
{

    setlocale(LC_ALL, "rus");
    Account arr_of_accounts[SIZE_ARR_OF_ACCOUNTS]; 
    int number_of_accounts = 0;// ?

    readFileAccounts(arr_of_accounts, number_of_accounts);
    bool flag_exit = true;//для выхода

    while (flag_exit) //пока flag_exit  равен правда,то
    {
        //MenuAccounts(); // для отображения пунктов выбора меню
        GlavnoeMenu();
        int item; //item - переменная для выбора пункта меню
        cin >> item; //просим ввести пункт выбора меню
        switch (item)
        {

        case 1:login(arr_of_accounts, number_of_accounts);

            break;

        case 2:flag_exit = false;
            break;

        default: 
            system("cls");
            cout << "Такого пункта меню нет" << endl;




    }
    writeFileAccounts(arr_of_accounts, number_of_accounts);
        system("pause");
}

    void GlavnoeMenu(){

    cout << "Авторизация" << endl;
    cout << "1: войти" << endl;
    cout << "2: выход" << endl;
  }


void login(Account *arr_of_accounts, int &number_of_accounts){

    cout << "Введите ваш логин " << endl;
    cin >> arr_of_accounts[number_of_accounts].login;

    cout << "Введите ваш пароль" << endl;
    cin >> arr_of_accounts[number_of_accounts].password;

    /*for (int i = 0; i < SIZE_ARR_OF_ACCOUNTS; i++)
    {*/
    readFileAccounts(arr_of_accounts, number_of_accounts);

    if (arr_of_accounts[number_of_accounts].login == arr_of_accounts[0].login &&   arr_of_accounts[number_of_accounts].password == arr_of_accounts[0].password)
    {
        cout << "Бобро пожаловать" << endl;
        system("cls");
        MenuAccounts();

    }

    else
    {
        system("cls");
        cout << "неверная пара логин и пароля" << endl;
    }
 }    
void MenuAccounts(){

    cout << "Меню для работы с учётными записями пользователей"<<endl;
    cout << "1: показать" << endl;
    cout << "2: добавить" << endl;
    cout << "3: удалить" << endl;
    cout << "4: редактировать" << endl;
    cout << "0: выход"<< endl;

}

void readFileAccounts(Account *arr_of_accounts, int &number_of_accounts)  
{

    ifstream fin(FILE_OF_ACCOUNTS, ios::in);//открыли файл для чтения

    if (!fin.is_open())
    {
        arr_of_accounts[0].login = "admin";
        arr_of_accounts[0].password = "admin";
        arr_of_accounts[0].role = 1;
        number_of_accounts = 1;
        writeEndFileAccounts(arr_of_accounts[0]);
    }
    else
    {
        number_of_accounts = 0;
        while (!fin.eof())
        {
            fin >> arr_of_accounts[number_of_accounts].login >> arr_of_accounts[number_of_accounts].password >> arr_of_accounts[number_of_accounts].role;
            number_of_accounts++;
        }

    }
    fin.close();// закрыли открытый файл
}

void writeFileAccounts(Account *arr_of_accounts, int number_of_accounts)//запись в файл (если что-то было в файле,данные исх. будут удалены)
{

    ofstream fout(FILE_OF_ACCOUNTS, ios::out);// Открыли файл для записи
    for (int i = 0; i < number_of_accounts; i++)
    {
        if (i < number_of_accounts - 1)
            fout << arr_of_accounts[i].login << " " << arr_of_accounts[i].password << " " << arr_of_accounts[i].role << endl;
        else
            fout << arr_of_accounts[i].login << " " << arr_of_accounts[i].password << " " << arr_of_accounts[i].role;

    }
    fout.close();
}
void writeEndFileAccounts(Account new_account)
{
    ofstream fout(FILE_OF_ACCOUNTS, ios::app);//открыли файл для дозаписи
    fout << endl;
    fout << new_account.login << " " << new_account.password << " " << new_account.role;

    fout.close();

}
void showAccounts(Account *arr_of_accounts, int number_of_acounts)
{
    cout << "Таблица учётных записей пользователей "<<endl;
            for (int i = 0; i < number_of_acounts; i++)
        cout << setw(4) << left << i + 1 <<
        setw(15) << left << arr_of_accounts[i].login <<
        setw(15) << left << arr_of_accounts[i].password <<
        setw(15) << left << arr_of_accounts[i].role << endl;
}

void addAccount(Account *arr_of_accounts, int &number_of_accounts)
{
    number_of_accounts++;
    cout << "Введите данные новой учётки" <<endl;
    cout << "Логин ";
    cin >> arr_of_accounts[number_of_accounts - 1].login;
    cout << "пароль ";
    cin >> arr_of_accounts[number_of_accounts - 1].password;
    cout << "Роль ";
    cin >> arr_of_accounts[number_of_accounts - 1].role;
    system("cls");
        cout << "Новая учётка добавлена !" << endl;
    cout << endl;
}

void delAccount(Account *arr_of_accounts, int &number_of_accounts)
{
    cout << "Введите номер удаляемой записи ";
    int del_item;
    cin >> del_item;
    for (int i = del_item - 1; i < number_of_accounts; i++)
        arr_of_accounts[i] = arr_of_accounts[i + 1];
    number_of_accounts--;
    system("cls");
    cout << "запись удалена !" << endl;
    cout << endl;

}

void updateAccount(Account *arr_of_accounts, int number_of_accounts)
{
    cout << "Введите номер редактируемой записи ";
    int upd_item;
    cin >> upd_item;

    cout << "отредактируейте данные учётной записи: "<<endl;
    cout << "логин:  !";
    cin>>arr_of_accounts[upd_item - 1].login;
    cout << "Пароль:  !";
    cin >> arr_of_accounts[upd_item - 1].password;
    cout << "роль:  !";
    cin >> arr_of_accounts[upd_item - 1].role;
        system("cls");
    cout << "запись отредактирована !" << endl;
    cout << endl;

}
1
  • Другой вопрос теперь
    – roman
    25 дек 2017 в 13:26

1 ответ 1

0

Для решения Вашей задачи, метод login должен выглядеть как-то так:

void login(Account *arr_of_accounts, int &number_of_accounts) {

        string inLogin;
        string inPassword;
        bool bIsLoggedIn = false;

        cout << "Введите ваш логин " << endl;
        cin >> inLogin;

        cout << "Введите ваш пароль" << endl;
        cin >> inPassword;

        /*for (int i = 0; i < SIZE_ARR_OF_ACCOUNTS; i++)
        {*/
        //Вы передаете аккаунты аргументом.
        //readFileAccounts(arr_of_accounts, number_of_accounts);

        for (size_t i = 0; i < number_of_accounts; i++) {
            if (inLogin == arr_of_accounts[i].login && inPassword == arr_of_accounts[i].password) {
                //Думаю здесь должен быть "глобальный" флаг либо сессия.
                bIsLoggedIn = true;

                cout << "Бобро пожаловать" << endl;
                system("cls");
                MenuAccounts();
                break;
            }
        }

        if (!bIsLoggedIn) {
            system("cls");
            cout << "неверная пара логин и пароля" << endl;
        }
}

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.