从文本文件c++中获取信息并进行匹配

getting information and matching it from text file c++

本文关键字:信息 获取 文本 文件 c++      更新时间:2023-10-16

我正在尝试执行一个创建新用户的程序。创建这个新用户需要用户名和密码。如果该用户名存在于文本文件中,程序将提示"存在一个现有用户名,并要求输入另一个用户名"用户名和密码将存储在一个文本文件中。

假设我的文本文件(userandPassword)已经有以下用户名和密码

按用户名密码格式化的文本文件

joe abc
jane def

我的代码有问题

如果我第一次输入joe,程序将提示"用户名已存在!">

如果我在那之后输入jane,程序将提示"用户名存在!">

但是,如果我在那之后输入joe,程序就会假设用户名joe不存在,并提示我输入密码。

我的输出(失败尝试)

Enter Desired UserName: joe
User Name existed!
Enter Desired UserName: jane
User Name existed!
Enter Desired UserName: joe
Enter Desired Password: 

期望输出

Enter Desired UserName: joe
User Name existed!
Enter Desired UserName: jane
User Name existed!
Enter Desired UserName: joe
User Name existed! 
Enter Desired UserName: jane
User Name existed!
Enter Desired UserName: joe
User Name existed! 
Enter Desired UserName: joe
User Name existed! 
Enter Desired UserName: jane
User Name existed!
Enter Desired UserName: bob
Enter Password: <---(password will only be prompted to key in if the username does not exist in the text file, otherwise it's will contiune to show "User Name existed" if username exist in text file)

这是我的代码

main.cpp

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string line, userName,userNameInFile,password;
ofstream fout;
ifstream readFile("userandPassword.txt");
cout << "Enter Desired UserName: ";
cin >> userName;
while (getline(readFile, line)) {
stringstream iss(line);
iss >> userNameInFile;
while (userNameInFile == userName)  {
cout << "User Name existed!" << endl;
cout << "Enter Desired UserName: ";
cin >> userName;
}
}
cout << "Enter Desired Password: ";
cin >> password;
fout.open("userandPassword.txt",ios::app);
fout << userName <<  ' ' << password << endl;
// close file.
fout.close();
cout << "nAccount Created and stored into TextFile!" << endl;
return 0;

}

我真的不确定是什么原因导致了这种情况。请帮忙。谢谢


更新答案*

string line, userName,userNameInFile,password;
ofstream fout;
vector<string> storeUserName;
ifstream readFile("userandPassword.txt");
while (getline(readFile, line)) {
stringstream iss(line);
iss >> userNameInFile;
storeUserName.push_back(userNameInFile);
}
cout << "Enter Desired UserName: ";
do {
for (int i =0; i<storeUserName.size(); i++) {
if (storeUserName[i] == userName) {
cout << "Existing UserName Existed!n";
cout << "Enter Desired UserName: ";
}
}
}while (cin >> userName);

首先从文件中读取用户"joe",并检查它是否与用户输入的用户名匹配。确实如此,然后您需要另一个用户名,即"jane"。它不匹配,因此内部循环中断,外部循环继续。这个循环从文件中读取下一个用户名,它与用户上次输入的用户名相匹配,因此您需要用户输入一个新用户名。这个新的名称与文件中的当前名称不匹配,因此内部循环中断,外部循环继续,但它在文件的末尾,因此中断,然后创建一个具有现有用户名的用户。

如果您在调试器中逐步执行代码,则很容易发现这个问题。

要解决这个问题,您可能需要分两步来完成。首先将文件读取到一个集合中,例如包含具有用户名和密码的结构的std::vector。然后,您向用户询问用户名,并在集合中查找。

将现有用户名读取到数组中,然后将输入的用户名与数组的元素匹配。

如果找到,请询问不同的用户名。

否则,请输入密码。