Reputation: 117
I got the random password generator program from here https://codereview.stackexchange.com/questions/138703/simple-random-password-generator And then I wanted to make a simple password program. Which generate 3 random char and uses sprint to combine "REG-" with the 3 random char.
REG-xxx
but the program doesn't compare it the way I expect it to do so. Do I miss some unexpected elements in the array ? Because I have read that char arrays counts newline or space as its elements too, Thanks in advance. Here's my code
#include<stdio.h>
#include<string.h>
#include<time.h>
int main(){
int i;
srand((unsigned int)(time(NULL)));
char pass[6];
char codebook[10];
char password[10];
printf("Press enter to get a three-character password\n");
getchar();
for (i = 0; i < 1; i++) {
pass[i] = rand() % 9;
char capLetter = 'A' + (rand() % 26);
pass[i + 2] = capLetter;
char letter = 'a' + (rand() % 26);
pass[i + 3] = letter;
printf("%d%c%c\n", pass[i], pass[i + 2], pass[i + 3]);
sprintf(codebook, "REG-%d%c%c\n", pass[i], pass[i+2], pass[i + 3]);
}
system("pause");
printf("%s\n", codebook);
fflush(stdin);
printf("Enter the password: ");
scanf("%s", password);
printf("\n%s\n", password);
printf("%s\n", codebook);
system("pause");
if(strcmp(codebook , password) == 0){
printf("password is correct\n");
} else{
printf("password is false\n");
}
return 0;
}
Upvotes: 1
Views: 41
Reputation: 26703
Here you print a newline into the password
sprintf(codebook, "REG-%d%c%c\n", pass[i], pass[i+2], pass[i + 3]);
You can later not enter that newline into the password and hence the comparision fails.
Changing to
sprintf(codebook, "REG-%d%c%c", pass[i], pass[i+2], pass[i + 3]);
solves the problem.
To find this kind of problem with whitespace in strings, I recommend to debug by printing the strings framing them in "impossible" but printable characters. As I recomended in a comment, I found the problen by introducing some additional prints (or modifying existing ones):
In this case, the helpful one was directly after the problematic sprintf()
:
printf("#%s#\n", codebook);
Upvotes: 1