程序在尝试访问文件时崩溃,fstream-C++

Program crashes when trying to access file, fstream --C++

本文关键字:崩溃 fstream-C++ 文件 访问 程序      更新时间:2023-10-16

我正在制作一个用户数据库。当我试图打开包含所有用户和密码的"dataBase.txt"时,控制台会弹出(这应该发生,因为它是一个控制台应用程序),但它表示程序已经完成。当我关闭它时,我的电脑告诉我程序崩溃了。函数保存在类中。

经过一些调试后,代码似乎在ifstream fin("dataBase.txt"); 上崩溃

编译器未返回任何错误

调用函数的代码为:

void User_Psw::UserCheck()
{
    // read from the database
    ifstream fin("dataBase.txt");
    while (!fin.eof())
    {
        fin >> Usernames[sizeOfDatabase] >> Password[sizeOfDatabase];
        sizeOfDatabase++; //The Number of lines in .txt
    }
    // rest of the program
    cout << "Username: ";
    cin >> username;
    getNameIndex();
    cout << "Password: ";
    cin >> password;
    if(!PasswordMatches())
    {
        cout << "Access denied";
    }
}

如果需要,我可以添加更多的代码片段

不要使用fin.eof()来控制循环。该函数只有在读取失败后才有用。

然而,崩溃的一个可能原因是您正在分配给Usernames[sizeOfDatabase],它可能超出了Usernames.capacity()。将和项附加到std::vector的规范方法是调用push_back()

由于您的容器是std::vector<std::string>,因此这是一种更好的方法。。。

std::string username, password;
while (fin >> username >> password)
{
    Usernames.push_back(username);
    Passwords.push_back(password);
    ++sizeOfDatabase;
}

当然,如果您想在读取文件后知道用户名或密码的数量,可以调用Usernames.size()(应该与Passwords.size()相同);这可以消除保持CCD_ 11的需要。

就我个人而言,我会使用一个容器来存放用户名和(加盐、加散列)密码,而不是两个单独的容器;std::map<std::string, std::string>或者std::unordered_map<std::string, std::string>,使得每个用户名的密码查找既好又快。

我认为您应该首先将其添加到ifstream的构造函数中,因为您还没有指定要打开文件进行输入:

ifstream fin( "dataBase.txt",  ifstream::in );
if( !fin.good() )
{
    cout << "Failed to open database file." << endl;
    return;
}

请参阅http://www.cplusplus.com/reference/fstream/ifstream/ifstream/以获取更多文献。