我有一个称为用户的结构,其中包含用户名信息:
struct User{
string name;
string type;
int credit;
bool loginState;
};
我的程序读取一个txt文件,并创建一个称为“用户”的User结构类型数组,以存储所有数据。我正在尝试创建一个删除用户的函数,因此在下面的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语句始终输出第二个条件。我怎样才能解决这个问题?
使用一个标志来指示该用户是否找到。
bool flag=false;
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;
flag=true;
break;
}
}
if(!flag){
cout << "Error: User does not exist";
}
希望能有所帮助...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句