【问题标题】:String compare in C for a passwordC中的字符串比较密码
【发布时间】:2016-04-01 15:52:02
【问题描述】:
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 时它应该可以正常运行。但是它总是返回错误的密码。有什么想法吗?

【问题讨论】:

  • 打印出cPassCode每个char的值。
  • 它正在打印正确的密码,但仍然说密码不正确
  • 从不在检查密码时使用 strcmp(),因为这会使您的应用程序容易受到计时攻击!为防止这种情况,您可以创建输入密码和真实密码的 md5/sha 哈希值并进行比较..
  • 注意:使用密码后,最好将缓冲区清零。然而,对于嵌入了"A23bc5" 的代码,这种安全性改进与@ensc 一样好主意。

标签: c string-comparison strcmp


【解决方案1】:

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

这会起作用

【讨论】:

  • 不可能这么简单——P肯定是先尝试了无效密码吧??
【解决方案2】:
if (iComparison = 0)

正在给变量赋值0,然后测试它,0计算为假。

 if (iComparison == 0)

正在检查变量是否为0,这可能是您的意思

【讨论】:

  • 没有人再打开警告了吗? :((
  • @MartinJames 通常编程新手不知道如何正确使用 IDE,这是有道理的。他们已经很难使用语言本身了:P
  • @MartinJames:根据我的经验,问题更多的是忽略警告
  • 是的,就是这样。谢谢!
【解决方案3】:

//字符串比较 C 中的密码直到 5 次尝试//

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

int main(){

int i,value;

char pass[10],id[10],key[]="1234";

printf("enter your id: ");
scanf("%s", id);

for(i=5;i>=0;i--){

printf("\nenter your password: ");
scanf("%s",pass);
value=strcmp(pass,key);

if(value==0){   
printf("matched");
return 0 ;
}

else{       
printf("not matched you have %d try left", i);
}
 }
return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多