简体   繁体   中英

How would i go about using 2 arrays in an && if statement

The first part of my program i creating 2 different arrays, the login id and password. After that has all been entered I would like the program to have 5 different IF statements that checks the 2 arrays to see if the ID and Password combinations are correct.

I am currently trying it like this for the first one with no success

#include <stdio.h>
#include <conio.h>
#include <string.h>

int main()
{
char id[5];
char password[8];
int i, j, k;
int access;
char c;

printf("Please enter your ID: ");
scanf("%5c", id);
printf("\nPlease enter your password: ");
for(k = 0; k < 8; k++)
{
    do
    {

        c = getch();
        if(c != '\n' || c != '\r')
        {
            password[k] = c;    
            putchar('*');
            break;
        }

    }while(c != '\n' || c != '\r');

}

for(i = 0; i < 8; i++)
{
    if(password[i] >= '0' && password[i] <= '9')
    {
        password[i] = (char)((password[i] - '0' + 4 )% 10 + '0');
    }

    if((password[i] >= 'a' && password[i] <= 'z') || (password[i] >= 'A' &&             password[i] <= 'Z') )
    {
        password[i] = (char)((password[i] - 'a' + 4) % 26 + 'a');
    }
}
if((strcmp(password, "abcdefgh") == 0) && (strcmp(id,"ft234")==0))
{
    access = 1;
    printf("Logged in.\n\n");

}    
else if((strcmp(password, "bcdefghi")==0) && (strcmp(id, "ty394")==0))
{
    access = 1;
    printf("Logged in.\n\n");

}
}

First problem

In C language you declare strings (arrays of characters) with double-quotes, not simple quotes.

Ex: char string[20] = "my string"

Using simple-quotes declares a single character.

Ex: char ch = 'a'

Second problem

You can't compare strings natively in low-level languages such as C language. You must use strcmp .

Solution

if ((strcmp(password, "string_passwd") == 0) && (strcmp(login, "string_login") == 0)) {
  <both password and login are ok>
} else {
  <one (or both) of password or/and login are not ok>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM