【发布时间】:2021-04-22 10:08:03
【问题描述】:
我创建了一个简单的登录/注册程序,可以读取和写入文件。它要求登录或注册,如果您选择注册,它会使用凭据(用户名和密码)写入单独的文本文件。如果您选择登录,它应该将您的凭据与文件中的所有凭据进行比较,并判断它是否是有效帐户。
这是代码(我知道的时间太长了;我只有 13 岁,所以我有点不擅长):
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
// Function that gets username and password from the user
vector<string> askForCredentials(){
string username, password;
cout << "Please enter a username: ";
getline(cin, username);
// Repeatedly asks the question until the input has no spaces
while(username.find(" ") != string::npos){
cout << "No spaces in the username!" << endl;
cout << "Please enter a username: ";
getline(cin, username);
}
//Again
cout << "Please enter a password: ";
getline(cin, password);
while(password.find(" ") != string::npos){
cout << "No spaces in the password!" << endl;
cout << "Please enter a password: ";
getline(cin, password);
}
return {username, password};
}
int main() {
//Declares variable for user input
string request;
cout << "Would you like to log in or sign up? ";
getline(cin, request);
//While the input is not log in or sign up it repeats the question
while(request != "log in" && request != "sign up"){
cout << "That is not a valid answer. Would you like to log in or sign up? ";
getline(cin, request);
}
//If the user wants to sign up...
if(request == "sign up"){
//Creates a vector calling the askForCredentials function which asks user for username and password
vector<string> credentials = askForCredentials();
//Opens accounts text file in append mode
ofstream accounts("current_accounts.txt", ios::app);
//If the file opens than say account created successfully, otherwise say couldn't make account
if(!accounts.is_open()){
cerr << "Couldn't create account" << endl;
return 0;
} else{
cout << "Account created successfully!" << endl;
}
//Appends username and password seperated by a space in the accounts file
accounts << credentials[0] << " " << credentials[1] << " " << endl;
accounts.close();
}
//If the user requests to log in...
if(request == "log in"){
//Creates vector with user input and says if file opens successfully or not
vector<string> credentials = askForCredentials();
ifstream accounts;
accounts.open("current_accounts.txt");
if(!accounts.is_open()){
cerr << "Couldn't log in" << endl;
return 0;
}
// Need help here
return 0;
}
}
我的问题部分在于日志。我基本上需要遍历 current_accounts 文件中的每一行凭据并将其与输入的凭据进行比较。如果有人可以帮助我解决这个问题,将不胜感激!如果您需要更多信息,我也可以回复。
哦,如果你能告诉我如何优化但保持可读性,我将不胜感激。
【问题讨论】:
标签: c++ string file vector input