程序在尝试访问文件时崩溃,fstream-C++
Program crashes when trying to access file, fstream --C++
我正在制作一个用户数据库。当我试图打开包含所有用户和密码的"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/以获取更多文献。
- 当回溯以零开始时,如何调试崩溃
- 内联映射初始化的动态atexit析构函数崩溃
- 在fstream期间忽略空行
- 执行函数时导致崩溃的变量
- 程序崩溃并显示"std::out_of_range"错误
- CoInitialize()在单独的线程上崩溃而不返回
- 使用调试/崩溃报告将应用程序部署到客户端
- 为什么所有C++编译器都会崩溃或挂起此代码
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 为什么我的多线程作业队列崩溃
- ExtractIconEx:可以工作,但偶尔会崩溃
- 为什么引用传递会导致此崩溃(C++)
- 试图创建流或fopen时程序崩溃
- 类对象数组的问题会导致崩溃
- STD :: FSTREAM在使用预先分配的内存时在Main之后崩溃
- 由于某种原因,FSTREAM测试程序崩溃
- 有人知道为什么Fstream在这条线上崩溃吗?
- 用fstream崩溃.exe读取txt文件
- 程序在尝试访问文件时崩溃,fstream-C++
- C++ 程序在使用 fstream fin 读取文件时崩溃