[英]Using strcmp() to compare two arrays of C-strings
我的項目是制作一個銀行帳戶程序,在該程序中,用戶輸入帳號和密碼即可在該程序中執行任何操作。 所使用的帳號和密碼必須存儲為C字符串(不允許使用字符串頭文件)。 我相信我遇到的問題是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);
。
最好這樣寫:
while (i < num_accounts)
{
if (strcmp(account, *(acc_num + i)) == 0)
{
// match found!
break;
}
i++;
}
您假設至少有一個帳戶,並且您也經常循環一次。 一種更安全的編寫方式如下:
for (int i = 0; i < num_accounts && !strcmp(account, accnum[i]); i++)
;
或相應的while
循環。 在此不宜do/while
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.