为什么strcmp()不会在密码工作?

时间:2012-07-17 17:30:13

标签: c string strcmp

为什么总是显示无效密码?它适用于我的其他程序,但在这个程序中却没有!我几乎无法弄清楚原因。

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#define MAXLTR 15
int login(void);
void welcome(void);
void gotoxy(int x,int y);

int main(void)
{   
    char password[MAXLTR];
    printf("\nEnter password: ");
    //scanf("\n%s",&password);
    ltrcntr = 0;
    while(buffer != 13)
    {
        buffer = getch();
        if(buffer == 13)
                  break;
        printf("\b**");
        password[ltrcntr] = buffer;
        ltrcntr++;
    }
    if(strcmp(password,"dlsu") == 0)
    {
        system("cls");
        welcome();
    }
    else
        printf("\nInvalid Password, please rerun the program.\n");


}
void gotoxy(int x, int y)
{
     HANDLE eric;
     COORD pogi;
     pogi.X = x;
     pogi.Y =y;
     eric = GetStdHandle
     (STD_OUTPUT_HANDLE);
     SetConsoleCursorPosition
     (eric, pogi);
}
int login(void)
{
    char password[MAXLTR],buffer;
    int ltrcntr = 0;
    printf("Enter password: ");
    while(buffer != 13)
    {
        buffer = getch();
        if(buffer == 13)
                  break;
        printf("\b**");
        password[ltrcntr] = buffer;
        ltrcntr++;
    }
    if(strcmp(password,"dlsu")==0)
        return 1;

}

void welcome(void)
{
    system("Color 4F");
    gotoxy(35,56);
    printf("\nWelcome to SPACE INVADERS!");
}

5 个答案:

答案 0 :(得分:3)

C字符串以NULL结尾(即最后一个字符为\0)。对字符串进行操作的所有C函数都希望这样,因为它是知道字符串结束位置的唯一方法。您可以使用任何内容填充数组,因为它未初始化。试试这个:

char password[MAXLTR] = {0};

strcmp期望以NULL结尾的字符串。此外,如果从未输入回车符(我甚至看不到buffer被宣布的位置...),您将超出密码缓冲区。

答案 1 :(得分:0)

在使用strcmp之前,您似乎没有使用空终止密码缓冲区。 C字符串实用程序期望字符串以空值终止。

读完密码的每个字符后,添加一个空字符,'\ 0'到密码:

password[ltrcntr] = '\0';

确保您为空字符允许数组大小的额外元素。

答案 2 :(得分:0)

可能是因为您的数组未终止NULL。要先将其归零,要么将循环更改为:

while(ltrcntr < MAXLTR - 1) // protect from password that's too long
{
    buffer = getch();
    if(buffer == 13)
              break;
    password[ltrcntr] = buffer;
    ltrcntr++;
    printf("\b**");
}
password[ltrcntr] = 0; // null terminate after last character

答案 3 :(得分:0)

您不能确保逐个字符地检查密码,终止'\ 0'在最后一个字符后面。密码不是以零终止的。这几乎就是全部。

答案 4 :(得分:0)

不需要按字符阅读字符。

fgets(password,MAXLTR,stdio);

在换行符或EOF之后停止,nul-终止字符串,并且不会超出缓冲区。