Zanderg 说他发现了问题,但他从不费心提及问题所在。不管任何可能仍然感兴趣的人,我都会继续发布它。
让我们试试下面的代码:
#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);
}
}
此外, yesgets
已被弃用。fgets
像我上面那样使用。
编辑(回答评论问题):
根据手册:
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.
我指的是sizeof(ans)
因为strcmp
将继续比较,直到遇到空字符。因此,在里面password
我们只想写到 的大小ans
,然后用空字符填充结尾。您还可以做的是更改它以使用strncmp
它来比较n
字节。在这种情况下,您不必告诉fgets
读取最多sizeof(ans)
字节。