Home > OS >  why strcmp function is not giving correct comparison result in c program
why strcmp function is not giving correct comparison result in c program

Time:09-08

So below is my source code in c in which i have used strcmp function to compare two strings

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

int main() {
unsigned char pass[100]="Try to hack me";
unsigned char input[100];

printf("Enter the secret string: ");
scanf("%s",input);

if(strcmp(pass,input))
printf("Wrong Password\nAccess Denied\n");
else
printf("Right password\nAccess Granted!!\n");

return 0;
}

when i run the compiled program it is giving wrong output, it suppose to give the right messasge but its giving wrong message. what is the problem here?

below is the output response of the program

professor@CTOS:~/Documents/Bnry/elf32bit/Module3/ch6$ ./crackme 
Enter the secret string: Try to hack me
Wrong Password
Access Denied
professor@CTOS:~/Documents/Bnry/elf32bit/Module3/ch6$ ./crackme 
Enter the secret string: Try to hack me
Wrong Password
Access Denied

CodePudding user response:

%s in scanf only reads until a white space character. From “Try to hack me”, it only reads “Try”. Use a different method to read the input line, possibly fgets, but be aware that fgets includes the new-line character that terminates the line.

When your program does not work, debug it. Either trace execution with a debugger or insert printf statements to show what it is doing. Inserting printf("The input is %s.\n", input); after the scanf would have revealed the problem.

  • Related