所以我的程序旨在让用户感到满意,并要求输入密码。一旦用户输入密码,它就会与我的预编码密码进行比较" ans []"如果密码与用户输入的密码匹配,则会打印欢迎问候语。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, const char * argv[])
{
char hello[] = "Hello! \nPassword Required:";
char password[50];
char ans[] = "Zanderg!";
printf(hello);
printf("\n");
gets(password);
if (strcmp(password, ans) != 0) {
do {
printf("%s Not correct.\n", password);
printf("Enter Password:\n");
gets(password);
getchar();
}while (strcmp(password, ans) != 0);
};
if (strcmp(password, ans) == 0) {
printf("welcome %s", password);
}
}
我的问题是,当我输入正确的密码时,我仍然会收到错误的密码&#34;信息。
我也得到了关于gets()是如何不安全的这个非常奇怪的消息,我想知道我是否有任何替代gets()或我如何摆脱我的程序中的此错误消息。我的编译器是Xcode。
答案 0 :(得分:1)
让我们尝试以下代码:
#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);
}
}
此外,不推荐使用是gets
。像我上面那样使用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)
个字节。