我的程序正在尝试创建一个新帐户,并将用户名与数据库中的用户名进行比较。 1个来自用户输入,另一个来自 vector 。我必须遍历 vector 并比较2个字符串。但是由于某些未知的原因,它仅比较FIRST值,而不比较 vector 内部的所有值。
这是我的代码:
我的LoginAcc.cpp
class AccountInfo {
public:
string username;
string password;
string type;
};
bool LoginAcc::checkAccountNameValid(string username) {
vector <AccountInfo> accInfo;
AccountInfo user;
ifstream UserDatabase("UserDatabase.txt");
string line = "";
while (getline(UserDatabase,line)) {
stringstream linestream(line);
getline(linestream,user.username,':');
accInfo.push_back(user);
}
UserDatabase.close();
for(vector<AccountInfo>::iterator itr = accInfo.begin(); itr != accInfo.end(); ++itr) {
if (username.compare((*itr).username) != 0)
return true;
else
return false;
}
我的main.cpp
case 'n':
while (!flag) {
cout << "Please enter a username with 8 characters. " << endl;
cout << "Username : ";
cin >> username;
if (username.length() != 8) {
cout << "Username does not meet the requirements" << endl;
cout << "Username : ";
cin >> username;
}
else {
valid = login.checkAccountNameValid(username);
if (valid == true) {
cout << "Please enter a password with 8 characters." << endl;
cout << "Password : " << endl;
cin >> password;
cout << "1. Student" << endl;
cout << "2. Lecturer" << endl;
cout << "3. Admin" << endl;
cout << "Please choose the category you belong to : ";
cin >> category;
login.createNewAcc(username,password,category);
}
else {
cout << "Username has been taken. Please choose another. " << endl;
cout << "Username : ";
cin >> username;
}
}
}
break;
我的“checkAccountNameValid”方法中的逻辑有问题。
谁能提出建议?
谢谢!
最佳答案
for(vector<AccountInfo>::iterator itr = accInfo.begin(); itr != accInfo.end(); ++itr)
{
if (username.compare((*itr).username) != 0)
return true;
}
return false;
等待返回
false
。我还认为您可能已将
!= 0
颠倒了:http://en.cppreference.com/w/cpp/string/basic_string/compare。安排代码的另一种方法可能会为您提供更多有关其工作原理的线索:
bool found = false;
for(auto itr = accInfo.begin(); itr != accInfo.end(); ++itr)
{
if (username.compare(itr->username) == 0)
found = true;
}
return found;
一种更现代的方法是
bool found = std::find_if(accInfo.begin(), accInfo.end(),
[] (AccountInfo const& ai) { return username == ai.username; });
或者,实际上,使用有助于查找的数据结构,如其他答案中所示的
std::map
关于c++ - 遍历类 vector 导致问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17925141/