Using strcmp() to compare two arrays of C-strings

My project is to make a bank account program where the user enters an account number and a password to do anything within the program. The account numbers and passwords used must be stored as C-strings (the string header file is not allowed). I believe that the problem I am having is with the strcmp function. Here is my function where the problem occurs.

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 and password are both arrays of C-strings. When I run/debug the program, it crashes at the first if statement. I guess my question is whether I'm using the strcmp function correctly or not, or if there is a problem with the pointers that I am using.

Answers


Your loop will run even when num_accounts is 0. Also, you're doing an out-of-bound array access by writing while (i <= num_accounts); instead of while (i < num_accounts);.

It would be better to write it like this:

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

You're assuming there is at least one account, and you're also looping once too often. A safer way to write it would be as follows:

for (int i = 0; i < num_accounts && !strcmp(account, accnum[i]); i++)
    ;

or the corresponding while loop. A do/while is not appropriate here.


Need Your Help

How to serve Flask static files using Nginx?

python nginx flask

I've a web application with this structure:

populate different data in listview according to spinner selection in android

android listview android-adapter

I have one spinner and I want to to populate the custom listview with the the data according to spinner selection. Data is coming from mysql database. Currently I am able to get the data from diffe...