0
\$\begingroup\$

I wrote this simple program to compare two strings ,I think it's working properly I just need to confirm that and also have few advices if possible

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

int main(){

    int value, lenght=0, i=0;
    char passwd[11], pass[11]="comptiatar";

    printf("enter ur passwd: ");
    scanf("%s", passwd);

    //value = strcmp(passwd,pass);

    while (passwd[i]!=0){
        lenght++;
        i++;
    }
    
    
    for (i=0;i<=lenght;i++){
        if (passwd[i]==pass[i])
            value=0;
        else {
            value=passwd[i]-pass[i];
            break;
        }
    }
    
    if (value)
        printf("\nwrong password\n\n");
    else
        printf("\nlogin successfully\n\n");
    printf("%d\n", value);

return 0;}

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Is it really necesary to "reinvent the wheel"? Instead of this:

while (passwd[i]!=0){
        lenght++;
        i++;
    }

could just use:

lenght=strlen(passwd);

And what the problem with just using strcmp? Also you can exit the for loop as soon passwd[i]!=pass[i].

Also what hapens if somebody type password longer then 10 characters? You should make passwd biger or check the return value of scanf.

\$\endgroup\$
3
  • \$\begingroup\$ I though it will be good if I create my own function \$\endgroup\$
    – UnderScore
    Commented Feb 5, 2022 at 17:31
  • \$\begingroup\$ @UnderScore Not realy, specially your implementation has no advantages. \$\endgroup\$
    – convert
    Commented Feb 5, 2022 at 17:52
  • \$\begingroup\$ thank you for your help \$\endgroup\$
    – UnderScore
    Commented Feb 7, 2022 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.