我有一个名为 users 的结构,其中包含用户名信息:
struct User{
string name;
string type;
int credit;
bool loginState;
};
我的程序读取一个 txt 文件并创建一个名为“users”的用户结构类型数组来存储所有数据。我试图创建一个删除用户的函数,所以在下面的 for 循环中我正在搜索字符串
userName
在用户数组中。如果用户名存在,则该用户帐户的所有信息都存储在用户临时文件中。否则会生成错误,指出输入的用户不存在。
string userName;
User temp;
cout<<"Please enter a username to delete:";
cin >> userName;
for(int i=0; i<usersSize; i++){
if((users[i].name).compare(userName) == 0){
temp.name = users[i].name;
temp.type = users[i].type;
temp.credit = users[i].credit;
temp.loginState = users[i].loginState;
}else{
cout << "Error: User does not exist";
}
}
我已经测试了我的程序,无论输入是什么,用户是否存在,if 语句总是输出第二个条件。我该如何解决这个问题?
最佳答案
您需要先检查用户是否存在,然后处理找到的用户。您的代码中的问题是 for 循环检查所有用户并为所有用户显示一条消息,但匹配的用户除外(如果有)。
检查这段代码:
bool userWasFound = false;
int i;
for(i=0; i<usersSize; i++){
if((users[i].name).compare(userName) == 0){
userWasFound = true;
break;
}
}
// If no user was found, 'userWasFound' will still be 'false' at this point
if(userWasFound){
temp.name = users[i].name;
temp.type = users[i].type;
temp.credit = users[i].credit;
temp.loginState = users[i].loginState;
}else{
cout << "Error: User does not exist";
}
关于c++ - If 语句第二个条件总是执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22778494/