我想尝试对登录/注册程序进行编码。使用外部.txt文件作为数据库,我想在其中保留“注册”用户和密码。 问题:我真的不能测试用户名的重复
// Currently stuck here
//Issue is that the if statment is not testing the way i want it to (comparing the usernames)
//The .txt file that i am using contains the content: "Usernames: "
//getline(myfile,line) returns "Usernames:" which is not really finding if there are any duplicates of usernames
ifstream myfile(filename.c_str());
while(getline(myfile,line)){
cout<< line;
if(line.find("Username: " + userregtry) == string::npos){
myfile.close();
ofstream writein(filename.c_str(),ios::app);
writein<< "Username: " << userregtry << "\n" ;
}
else{
cout<< "\nThis username has been taken\nPlease try another username: ";
}
}
答案 0 :(得分:0)
假设每行有一个名字
有几个问题:
如果名称不在第一行,则认为该名称不存在,然后关闭文件,停止搜索
如果第一行中存在该名称,则警告您,然后继续;如果第二行中没有该名称的先验,则您认为该名称不存在
如果文件为空,它将保持为空
您需要查看所有行,然后才能考虑该名称不存在。
解决方案:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename = "/tmp/foo";
string userregtry;
cout << "\nPlease enter username: ";
for (;;) {
if (!(cin >> userregtry))
break;
ifstream myfile(filename.c_str());
bool found = false;
string line;
while (getline(myfile,line)) {
if (line.find("Username: " + userregtry) != string::npos) {
found = true;
break;
}
}
myfile.close();
if (found)
cout<< "\nThis username has been taken\nPlease try another username: ";
else {
ofstream writein(filename.c_str(),ios::app);
writein<< "Username: " << userregtry << "\n" ;
break;
}
}
return 0;
}
从空文件执行:
/tmp % ./a.out
Please enter username: aze
/tmp % ./a.out
Please enter username: aze
This username has been taken
Please try another username: qsd
/tmp % ./a.out
Please enter username: qsd
This username has been taken
Please try another username: aze
This username has been taken
Please try another username: iop
/tmp % cat foo
Username: aze
Username: qsd
Username: iop
假设文件包含一行Usernames: name1 name2 ... namen
有几个问题:
您的代码没有找到名称,除非它位于第一个位置
添加新名称时,所有其他名称都会丢失
用户名或用户名 s 吗?
不终止唯一行的解决方案:
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename = "/tmp/foo";
string line;
{
ifstream myfile(filename.c_str());
if (getline(myfile,line))
line += ' '; // to have a space before and after each name including the last
}
string userregtry;
cout << "Please enter username: ";
for (;;) {
if (!(cin >> userregtry))
return 0;
if (line.find(' ' + userregtry + ' ') != string::npos)
cout << "This username has been taken\nPlease try another username: ";
else {
ofstream writein(filename.c_str(),ios::app);
if (line.empty())
writein << "Usernames: ";
else
writein << ' ';
writein << userregtry;
return 0;
}
}
}
从空文件执行:
Please enter username: aze
/tmp % ./a.out
Please enter username: aze
This username has been taken
Please try another username: qsd
/tmp % ./a.out
Please enter username: aze
This username has been taken
Please try another username: qsd
This username has been taken
Please try another username: wxc
/tmp % cat foo ; echo "#"
Usernames: aze qsd wxc#