This question has already been answered:
- Error saving complex structure in file 1 response
There is a structure
struct User { string login; string password; }; The goal is to make a primitive user authorization. Those. a file is created, a filled object of the above structure is written to it, and on subsequent launches a login + password is requested, the data from the file is read and compared. Code:
#include <iostream> #include <windows.h> #include <fstream> #include <vector> #include <string> using namespace std; struct User { string login; string password; }; void main () { SetConsoleCP (1251); // установка универсальной кодировки SetConsoleOutputCP (1251); string path; int realsize=0; User u; vector <User> U; bool exit = false; do { system("cls"); cout<<"Укажите, на каком диске находится файл с регистрационными данными:\n"; getline(cin, path); path += ":\\users.txt"; ifstream fin(path, ios_base::binary | ios_base::in); if (fin.is_open()) { cout<<"Отлично, ваш файл найден!\n"; fin.read((char*)&u, sizeof(User)); U.push_back(u); fin.close(); cout << "Введите логин:\n"; getline(cin, u.login); cout << "Введите пароль:\n"; getline(cin, u.password); if (!U.at(0).login.compare(u.login) && !U.at(0).password.compare(u.password)) { cout << "Вы авторизованы!\n"; } else { cout << "Вы не авторизованы!\n"; } exit = true; } else { cout << "Файл не найден и будет создан"; ofstream fout (path, ios_base::binary | ios_base::out); if (fout.is_open()) { cout << "Введите логин:\n"; getline(cin, u.login); cout << "Введите пароль:\n"; getline(cin, u.password); fout.write((char*)&u, sizeof(User)); fout.close(); cout << "Файл создан и данные внесены!\n"; } else { cout << "Ошибка при создании файла! Работа приложения будет завершена.\n"; exit = true; } } } while(!exit); system("pause"); } The trouble is that when executing this code, an error appears:
Unhandled exception at address 0x0FDECCC8 (msvcp110.dll) in test.exe: 0xC0000005: access violation when reading at 0x0067ADE4.
Call stack frames:
It was established through experiments that replacing the use of a vector with a simple dynamic array does not affect the error (that is, it still appears), but replacing the use of string with char * eliminates the manifestation of this error. Googling, I came to the conclusion that there is some kind of error in the string destructor (I could be wrong). Can someone clarify the situation and give recommendations on the correct use of the string type in this kind of tasks?
