1

我正在尝试制作一个简单的程序,要求用户输入姓名、电子邮件和密码作为注册的一部分,然后让他再次输入电子邮件和密码以登录。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
        struct NewUserinfo{
        int age;
        char name[30], email[50], pass[16];
    }; 


    char e1[100], p1[16], e2[100], p2[16], name1[30], userprompt;
    printf("Welcome! Would you like to create an account? (y/n) ");
    CheckPrompt:
    scanf(" %c", &userprompt);
    switch(userprompt){
    case 'y':
        goto newUser;
        break;
    case 'n':
        goto caseN;
        break;
    default:
        printf("Invalid option. Please press \"y\" or \"n\".\n");
        goto CheckPrompt;
        break;
    }

    caseN:
        printf("Do you already have an account? (y/n) ");
        scanf(" %c", &userprompt);
         switch(userprompt){
    case 'y':
        goto alreadyUser;
        break;
    case 'n':
        goto end;
        break;
    default:
        printf("Invalid option. Please press \"y\" or \"n\".\n");
        goto caseN;
        break;
         }




    newUser:
        printf("Hello there. ");

        struct NewUserinfo user1;
            printf("What's your name? ");
            scanf("%s", user1.name);
            strcpy(name1, user1.name);
            printf("Your name is %s. ", user1.name);
            printf("What's your email? ");
            scanf("%s", e1);
            strcpy( user1.email, e1);
            printf("Your email is %s. What's your password? ", e1);
            scanf("%s", p1);
            strcpy(user1.pass, p1);
            printf("Your password is %s. \n", p1);
            printf("Thank you for signing up! Try our log in feature now.\n");

    alreadyUser:
        printf("Welcome back!\n");
        struct NewUserinfo user2;
            printf("What's your email? ");
            scanf("%s", e2);
            strcpy(user2.email, e2);
            printf("Your email is %s. What's your password? ", e2);
            scanf("%s", p2);
            strcpy(user2.pass, p2);
            printf("Your password is %s. ", p2);
            if(e1 == e2 && p1 == p2){
                printf("Welcome, %s.", name1);
            }
            else if(p1 != p2){
                printf("Wrong password.");
                goto alreadyUser;
            }
            else if(e1 != e2){
                printf("Invalid email.");
                goto alreadyUser;
            }
            else goto end;

    end:
        printf("Thank you for your time, %s. ", name1);
    getchar();
    return 0;
}

整个过程都很好,直到它到达登录部分,即使我输入相同的“电子邮件”和“密码”(在我的情况下,我只是在它们两个字面上输入 gg),输出总是“错误密码”。如果我将 if 语句检查电子邮件放在 if 语句上方检查密码,它会立即更改为永久“无效电子邮件”,程序将不断要求我输入正确的“电子邮件”和“密码” . 我在这里做错了什么吗?

4

1 回答 1

3

使用 strcmp。替换您的所有陈述:

if(e1 == e2 && p1 == p2){

经过

if((strcmp(e1, e2) == 0) && (strcmp(p1, p2) == 0)) {

您可以在此处找到有关 strcmp 的有用参考。建议:避免使用命令 goto。更喜欢使用函数,它使您的代码更易于理解:)。

于 2021-09-17T18:49:21.207 回答