如何将输入与文件中的内容相匹配?我需要一个更好的解释

How do I match input to contents in a file? I need a better explanation.

本文关键字:解释 更好 一个 输入 文件      更新时间:2023-10-16

下面的代码进一步解释了这一点。询问用户是否有帐户,如果有,则代码应该查看文件并将用户输入与文件中的内容相匹配。我读过应该与getline一起使用的内容,但我不理解其中的部分。实际上,我是从一个不想教任何书中没有的东西的老师开始C++的。

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string username[20];
string password[8];
string answer;
string line;
string fname, lname;
ifstream ifile("Users.text");
ifile.open("Users.txt");
ofstream ofile("Users.txt");
ofile.open("Users.txt");
cout<<"Do you have an account with us?"<<endl;
cin >> answer;
if(answer == "yes" || answer == "Yes")
{
cout<<"Please enter your username."<<endl;
cin>>username;
cout<<"Please enter your password."<<endl;
cin>>password;
while(getline(ifile, line))
{
istringstream iss(line);
if(getline(iss, username, ','))
{
//some magic is supposed to happen here. 
}
} 
}else if(answer == "no" || answer == "No") {
cout<<"Name: "; 
cin>>fname>>lname;
}

return 0;
}

这些行:

std::string username[20];
std::string password[8];

是个大问题。它们声明字符串数组。由于你从未使用过这样一个数组的任何元素,只需读取1个用户名/密码,似乎有人把C代码翻译成了C++。只需放下阵列尺寸:

std::string username;
std::string password;

至于"魔法",请点击评论中的链接。我们无能为力,因为我们不知道文件里有什么WAIT*我们**确实知道文件中有什么,因为

std::ofstream ofile("Users.txt");
ofile.open("Users.txt");

覆盖它。所以文件是空的。至少要纠正这一点。

更多备注

if (getline(iss, username, ',')) {

覆盖用户输入的用户名。。。也许就是数组的用途?无论如何,看起来你不需要来存储文件²的内容,所以只需使用一个单独的变量:

在Coliru上直播

#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string username;
std::string password;
std::string fname, lname;
std::ifstream ifile("Users.txt");
//std::ofstream ofile("Users.txt");
//ofile.open("Users.txt");
std::cout << "Do you have an account with us?" << std::endl;
std::string answer;
std::cin >> answer;
if (answer == "yes" || answer == "Yes") {
std::cout << "Please enter your username." << std::endl;
std::cin >> username;
std::cout << "Please enter your password." << std::endl;
std::cin >> password;
std::string line;
bool verified = false;
while (getline(ifile, line)) {
std::istringstream iss(line);
std::string u, pw;
if (getline(iss, u, ',') && getline(iss, pw, 'n')) {
if (u == username && pw == password) {
verified = true;
break;
}
}
}
if (verified) {
std::cout << "Welcome back, " << username << "n";
} else {
std::cout << "Username not valid or password incorrectn";
}
} else if (answer == "no" || answer == "No") {
std::cout << "Name: ";
std::cin >> fname >> lname;
}
}

在C中,一种常见的模式是使用char[]缓冲区来存储原始字符串内容

²或者你可能需要书中没有教过的数据结构…:)