我的项目是制作一个银行账户程序,用户在该程序中输入帐号和密码即可执行任何操作。使用的帐号和密码必须存储为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/