c++ - If 语句第二个条件总是执行

标签 c++ string struct

我有一个名为 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/

相关文章:

指向字符串和 append() 方法的指针的 C++ 数组

c - 如何将 argv[k] 变成另一个字符串?

c++ - 为函数内部的结构分配和初始化值

c++ - 获取/设置函数以更改文本和颜色

c++ - 这个 opencv 函数如何在 C++ 中解释

Android:JSON 字符串数据与其他字符串比较

c - 没有pointee指针不返回null?

c - 从文件加载 C 结构

c++ - 到第一个可行解的 CPLEX 时间

c++ - Xerces DOMNode 将节点名称返回为#Text