简体   繁体   English

比较两个字符字符串以获取C中的密码

[英]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: 我一直在尝试比较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;
    }

strcmp works with null terminated strings. strcmp使用以null终止的字符串。 You need a \\0 character at the end of each string, and each string in this case should be 5 characters long. 每个字符串的末尾都需要一个\\0字符,在这种情况下,每个字符串的长度应为5个字符。

key[5]="tres";

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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