Doesnt从文件中读取数据
Doesnt read data from file
我做错了什么?我输入了正确的凭据,程序一直在说"无效的用户名或密码!"
void user::login()
{
string username, uname;
string password, pword;
cout << "Enter your username: n";
cin >> uname;
cout << "Enter your password: n";
cin >> pword;
ifstream data("data.txt");
if (data.is_open())
{
while (!data.eof())
{
data >> username >> password;
if (uname == username && pword == password)
{
cout << "Login successfully!n";
Sleep(2000);
mainMenu();
}
else if (uname != username || pword != password)
{
cout << "Invalid username or password!n";
Sleep(2000);
login();
}
}
data.close();
}
}
请参阅我的内联评论:
#include <string>
#include <iostream>
#include <fstream>
// You should not use using namespace std! In here only for brevity.
using namespace std;
// Use a proper API: return account name on success, empty string otherwise.
// Throw an exception on error.
string login() throw (const char*)
{
// embrace C++11!
if (ifstream data {"data.txt"}) {
string username, uname;
string password, pword;
// Always test if the IO is broken!
if (!((cout << "Enter your username: n") &&
(cin >> uname) &&
(cout << "Enter your password: n") &&
(cin >> pword))) {
throw "Could not get user credentials.";
}
// debug output, remove in production:
cerr << "Credentials: " << uname << " (" << pword << ")" << endl;
// read a line from data.txt
while (data >> username >> password) {
// debug output, remove in production:
cerr << "Read: " << username << " (" << password << ")" << endl;
// compare input:
if ((uname == username) && (pword == password)) {
return username;
}
}
// no input matched
return "";
// no need to explicitly close the stream
} else {
throw "Password file could not be opened.";
}
}
int main() {
string account_name;
try {
// The caller should include a loop, not the login function.
account_name = login();
} catch (const char *message) {
cerr << "Error: " << message << endl;
return 1;
}
if (!account_name.empty()) {
cout << "Hello, " << account_name << endl;
} else {
cout << "Could not authenticate!" << endl;
}
return 0;
}
data.txt:
Neuroosi hunter2
Kay supersecret
Arunmu hello
crashmstr password1234
相关文章:
- 如何在ros2中从rosbag2读取数据
- OpenCV 和从 OutputArrays 或 (Mat) 读取数据
- 使用C++从磁卡读卡器MT188读取数据
- HDF5 简单读取数据集失败
- 嵌套结构,从由空行分隔的文件中读取数据
- 不要从输入队列套接字读取数据
- 从文件中读取数据,操作员>>
- 如何从excel文件中读取数据并存储到变量中?
- C++:从文件中读取x y数据会产生无限循环吗
- 无法通过FT232RL读取数据
- 如何从QNetworkReply读取数据?
- C++ 逐行从文件(包含空格)读取数据
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 我们可以从 TXT 文件中读取数据并使用 C 和 C++ 将其保存到 SQL 数据库吗?
- 从多个 tcp 连接读取数据
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- Qt TCP服务器不从客户端读取数据
- 累积从 C++11 中的文件中读取数据的整数
- 从 txt 文件中读取数据的最简单方法
- 从 txt 文件中读取数据的 Getline