C中的字符串比较密码

时间:2016-04-01 15:52:02

标签: c string-comparison strcmp

void main()
{
    Password();
}


int Password()
{
    // Declare local variables//
    char cPassCode[] = "String";
    int iFlag, iComparison = 0;

    // Run the code to check the password//
    while (iFlag = 0)
    {
        printf("Please enter the password: ");
        scanf("%s", cPassCode);
        iComparison = strcmp(cPassCode, "A23bc5");
        if (iComparison = 0)
        {
            ArrayPrinter(Array);
            iFlag = 1;
        }
        else
        {
            printf("Wrong password");
            iFlag = 0;
        }
        return(iFlag);
    }
}

我编辑了代码部分,据我所知,当输入密码A23bc5时它应该正常运行。但是它始终返回错误的密码。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

如果字符串相等,

strcmp函数返回0。您应该编辑条件块。

编辑:

实际上你也有非常基本的语法问题。

  int Password()
{
//declare local variables//
char cPassCode[] = "String";
int iFlag=0, iComparison = 0;

//Run the code to check the password//
while (iFlag == 0)
{
    printf("Please enter the password: ");
    scanf("%s", cPassCode);
    iComparison = strcmp(cPassCode,"A23bc5");
    if (iComparison == 0)
    {
        printf("\n Accepted");
        iFlag = 1;
    }
    else
    {
        printf("Wrong password");
        iFlag = 0;
    }
    return(iFlag);
}
}

int main()
{


 Password();

 return 0;
}

这将有效

答案 1 :(得分:1)

if (iComparison = 0)

为变量赋值0然后测试它,0的计算结果为false。

 if (iComparison == 0)

检查变量是否为0,这可能是你的意思