0

因此,我的程序旨在为用户提供出色的服务并要求输入密码。一旦用户输入密码,它就会与我的预编码密码“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);
}
}

我的问题是,当我输入正确的密码时,我仍然会收到“密码错误”的消息。

我也收到了关于gets() 不安全的非常奇怪的消息,我想知道是否有gets() 的替代方法,或者如何在程序中消除此错误消息。我的编译器是 Xcode。

4

1 回答 1

1

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像我上面那样使用。

编辑(回答评论问题):

  1. 根据手册:

    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.

  2. 我指的是sizeof(ans)因为strcmp将继续比较,直到遇到空字符。因此,在里面password我们只想写到 的大小ans,然后用空字符填充结尾。您还可以做的是更改它以使用strncmp它来比较n字节。在这种情况下,您不必告诉fgets读取最多sizeof(ans)字节。

于 2014-04-16T07:25:50.653 回答