Zanderg said that he found the problem, but he never bothered to mention what it was. I'll go ahead and post it regardless for anybody who might still be interested.
Let's try the following piece of code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, const char * argv[])
{
char password[50];
char ans[] = "Zanderg!";
printf("Hello! \nPassword Required:\n");
fgets(password, sizeof(ans),stdin);
if (strcmp(password, ans) != 0) {
do {
printf("%s Not correct.\n", password);
printf("Enter Password:\n");
fgets(password, sizeof(ans),stdin);
getchar();
}while (strcmp(password, ans) != 0);
};
if (strcmp(password, ans) == 0) {
printf("welcome %s", password);
}
}
Also, yes gets
is deprecated. Use fgets
as I did above.
EDIT (To answer the comment questions):
As per manual:
char* gets(char *s)
:gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with a null byte ('\0'). No check for buffer overrun is performed. Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
char *fgets(char *s, int size, FILE *stream)
:fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
I am referring to
sizeof(ans)
becausestrcmp
will continue comparing until it encounters the null character. Therefore, insidepassword
we only want to write up to the size ofans
, and then fill the end with the null character. What you can also do is change this to usestrncmp
which does a comparison up ton
bytes. In that case, you don't have to tellfgets
to read in up tosizeof(ans)
bytes.