在C中比较两个char字符串的密码

时间:2015-04-11 19:49:11

标签: c char passwords compare

我一直在尝试比较C中的两个char变量,一个是关键字,另一个是用户输入的密码,但尽管两者都相同,但它不允许我进入。这就是代码:

#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;
    }

2 个答案:

答案 0 :(得分:2)

strcmp使用空终止字符串。在每个字符串的末尾需要一个\0字符,在这种情况下每个字符串应该是5个字符长。

答案 1 :(得分:1)

key[5]="tres";

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

相关问题