简体   繁体   中英

Comparing two char strings for a password in C

I've been trying to compare two char variables in C, one being the keyword, and the other being the password the user inputs, but despite both being the same, it doesn't let me in. This is the code:

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

int main(){
    char pass[4], key[4]="tres";
    start:
    clrscr();
    printf("Write your password: ");
    scanf("%s", &pass);
    if (strcmp(pass,key)!= 0){
        printf("\nWrong password, try again.");
        getch();
        goto start;
    }else if(strcmp(pass,key) == 0){
        printf("Welcome!");
        getch();
        clrscr();
        //here goes the rest of the program
    }
    return 0;
    }

strcmp works with null terminated strings. You need a \\0 character at the end of each string, and each string in this case should be 5 characters long.

key[5]="tres";

您必须将数组的大小增加1以存储字符串字符\\0的结尾

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