c++ - 使用 strcmp() 比较两个 C 字符串数组

标签 c++ c-strings

我的项目是制作一个银行账户程序,用户在该程序中输入帐号和密码即可执行任何操作。使用的帐号和密码必须存储为C-strings(不允许使用字符串头文件)。我相信我遇到的问题是 strcmp 函数。这是我出现问题的功能。

void get_password(int num_accounts, char **acc_num, char **password)
{
    char account[ACCOUNT_NUMBER];
    char user_password[PASS_LENGTH];

    std::cout << "\nEnter the account number: ";
//  std::cin.getline(account, ACCOUNT_NUMBER);
    std::cin >> account;

    int i = 0;

    do
    {
        if (strcmp(account, *(acc_num + i)) != 0)
        {
            i++;
        }
        else
            break;
    } while (i <= num_accounts);

    if (i == num_accounts)
    {
        std::cout << "\nCould not find the account number you entered...\nExiting the program";
        exit(1);// account number not found
    }

    std::cout << "\nEnter the password: ";
//  std::cin.getline(user_password, PASS_LENGTH);
    std::cin >> user_password;

    if (strcmp(user_password, *(password + i)) != 0)
    {
        std::cout << "\nInvalid password...\nExiting the program";
        exit(1);// incorrect password
    }
    else
    {
        std::cout << "\nAccount number: " << account
        << "\nPassword: " << user_password << "\n";
        return;
    }
}

acc_num 和 password 都是 C 字符串数组。当我运行/调试程序时,它在第一个 if 语句处崩溃。我想我的问题是我是否正确使用了 strcmp 函数,或者我使用的指针是否有问题。

最佳答案

即使在 num_accounts 时你的循环也会运行为 0。此外,您正在通过编写 while (i <= num_accounts); 进行越界数组访问。而不是 while (i < num_accounts); .

最好这样写:

while (i < num_accounts)
{
    if (strcmp(account, *(acc_num + i)) == 0)
    {
        // match found!
        break;
    }
    i++;
}

关于c++ - 使用 strcmp() 比较两个 C 字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35248084/

相关文章:

c++ - 每个选项卡只看到一次 onload 事件

c++ - 关于 ofstream 的模棱两可的警告,但不是 ostream 的警告。有什么不同?

c++ - Boost 库不使用 G++ 在 Netbeans 中编译

c++ - 在数字常量之前需要不合格的 id。 - 阿杜诺

c++ - 为什么 std::strlen() 在不终止空字符的情况下处理 char 数组?这是编译器优化吗?

c - 字符串终止 - char c=0 与 char c ='\0'

c++ - 调试嵌入式 Lua

c++ - 使用 String 的 c_str() 并分配给 char const* : assignment of read-only location

c++ - 获取指向包含十六进制值的 C 字符串的指针

swift - 如何在 Swift 中获取 CString (UTF8String) 的长度?