I have this simple problem that gets an input from the user using a function then checks if the input is 'equal' to the "password". However, strcmp would never return my desired value, and the culprit is somewhere in my loop that uses getch() to take each character separately and add them to the character array. I found this out by having printf display the character array. If I type in pass word, the function would display it as pass word ". I have no idea on why the closing double quote and a whitespace was included in the array right after the word I typed in. Any idea? Here's the code. Thanks.
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <string.h>
int validateUser();
int main()
{
for(int x = 0;x<2;x++)
{
if(validateUser())
{
system("cls");
printf("\n\n\t\t** Welcome **"); break;
}
else
{
system(开发者_运维问答"cls");
printf("\n\n\t\tIntruder Alert!");
system("cls");
}
}
system("PAUSE>nul");
return 0;
}
int validateUser()
{
char password[9];
char validate[] = "pass word";
int ctr = 0, c;
printf("Enter password : ");
do
{
c = getch();
if(c == 32)
{
printf(" ");
password[ctr] = c;
}
if(c != 13 && c != 8 && c != 32 )
{
printf("*");
password[ctr] = c;
}
c++;
}while(c != 13);
return (!strcmp(password, validate));
}
- Your char array
password
does not have a terminating null char. - You need to ensure that you don't
stuff more than 8 char into
password
- Also
c++
should bectr++
.
do {
// stuff char into password.
ctr++;
}while(c != 13 && ctr <8);
password[ctr] = 0;
You're incrementing c in your loop. You should be incrementing ctr. Also, all the stuff everyone else has said (null terminator, only 8 characters, etc).
getch()
is a function defined in a non-standard header <conio.h>
. Relying on non-standard features is not recommended when you want your code to be portable. :)
do {
// stuff char into password.
++ctr;
} while(c != 13 && ctr < 9);
password[ctr] = '\0';
精彩评论