好的,我正在尝试编写一个程序,它可以接收密码和用户名并将它们存储在一个文件中(我还没有写它们写入文件的部分,稍后会写),但是我的代码中读取文件的部分导致它无法工作(没有输出)即使它在VS代码中编译没有错误。老实说,我也不完全理解我写的东西(我只是看了一个youtube视频),所以我一定是错过了一些代码。为了获得更多信息,我使用C++20和clang ++作为我的编译器。我把我的代码贴在下面以供参考。
#include <iostream>
#include <cstdio>
#include <vector>
#include <fstream>
using namespace::std;
class user {
private:
string username;
string password;
public:
user(string user, string pass) {
username = user;
password = pass;
}
void SetUsername(string user) {
username = user;
}
void SetPassword(string pass) {
password = pass;
}
void ChangeUsername(string user) {
username = user;
}
void ChangePassword(string pass) {
password = pass;
}
string GetUsername() {
return username;
}
string GetPassword() {
return password;
}
};
int main() {
string listUsernames[1000];
string listPasswords[1000];
vector <user>list;
string username;
string password;
string prompt;
bool loginSuccess = false;
bool success = false;
int counter = 0;
int lines = 0;
/*
This part is like messsing it up
Starting from here:
*/
ifstream file;
file.open("usernames.txt");
while(!file.eof()) {
getline(file, listUsernames[lines]);
lines++;
}
file.close();
lines = 0;
file.open("passwords.txt");
while(!file.eof()) {
getline(file, listPasswords[lines]);
lines++;
}
file.close();
for(int i = 0; i < lines; i++) {
user oldUser(listUsernames[i], listPasswords[i]);
list.push_back(oldUser);
}
/*
Ending here
*/
cout << "\tWelcome user! Please choose to login or create an account below.\n";
do{
cout << "\tType \"Login\" to login or \"Create\" to create a new account\n";
cin >> prompt;
if(prompt == "Login") {
do{
cout << "Username: ";
cin >> username;
cout << "Password: ";
cin >> password;
for(int i = 0; i < list.size(); i++) {
if(username == list[i].GetUsername() && password == list[i].GetPassword()) {
cout << "Hello " << list[i].GetUsername() << "!\n\n";
loginSuccess = true;
success = true;
}
}
if(!loginSuccess) {
cout << "Incorrect username or password";
counter++;
if(counter < 2) {
cout << ", please try again.\n";
}
else {
cout << "\nMaybe you should try creating an account! \n";
}
}
} while(!loginSuccess && counter < 2);
}
else if(prompt == "Create") {
string newUsername;
string newPassword;
cout << "What would you like your username to be? Please enter: ";
cin >> newUsername;
cout << "What would you like your password to be? Please enter: ";
cin >> newPassword;
user newUser(newUsername, newPassword);
list.push_back(newUser);
cout << "Success!\n";
ofstream myfile;
myfile.open("usernames");
myfile << newUsername;
myfile.close();
myfile.open("passwords");
myfile << newPassword;
myfile.close();
}
else {
cout << "Sorry, that input was not understood\n";
cout << "Please try again\n";
}
} while(!success);
return 0;
}
2条答案
按热度按时间mefy6pfw1#
你的错误:
while (!file.eof())
(link)修复后:
8i9zcol22#