首页 > 解决方案 > 跳过我输入用户名的输出

问题描述

我需要制作一个日记/计划者,在那里我可以有一个用户名和密码登录并设置一个登录名和帐户,如果你还没有的话。我需要稍后才能使用它登录并访问我的日记。在那里我可以输入条目并保存它。这样当我退出程序并再次启动程序时,一旦我登录,我就可以再次访问计划器。

所以我的问题是,为了设置我的帐户,我需要允许用户输入用户名和密码,但是当我启动程序时,它会跳过我可以输入用户名的部分并直接进入密码。编码:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 1000

void signUp (char username [SIZE], char password [SIZE], char name [SIZE], int age) {
    printf("Sign Up Procedure: \n");
    printf("\nPlease enter your username: ");
    gets(username);
    printf("\nPlease enter a password: ");
    gets(password);
    printf("\nEnter your full name: ");
    gets(name);
    printf("\nEnter your age: ");
    scanf("%d", &age);

    printf("Username: %s, Password: %s, Full Name: %s, Age: %d", username, password, name, age);
}

void logIn(char username [SIZE], char password [SIZE]) {

}

int main() {
    printf("1. Log In\n");  // Enter 1 for logging in
    printf("2. Sign Up\n"); // Enter 2 for signing up
    int choice;
    scanf("%d", &choice);

    char username [SIZE];
    char password [SIZE];
    char name [SIZE];
    int age;

    int keepGoing = 0;

    while (keepGoing == 0){
        switch (choice) {
        case (1):
            logIn (username, password);
            keepGoing = 1;
            break;
        case (2):
            signUp (username, password, name, age);
            keepGoing = 1;
            break;
        default:
            printf("Please enter a choice from the given options");
            keepGoing = 0;
            break;
        }
    }

    FILE * pfile;

    pfile = fopen("Planner.txt", "w");

    fputs("Planner", pfile);

    fclose(pfile);

    return 0;
}

标签: c

解决方案


你的第一个scanf()

scanf("%d", &choice);

正在读取一个整数,因此它将换行符留在输入缓冲区中。

然后当您尝试获取用户名时:

gets(username);

它拾取该换行符并将其分配给username. 我建议阅读C输入以及为什么scanf()使用起来可能很危险和棘手,特别是在混合整数和字符串输入以及将其与其他C输入函数一起使用时。


推荐阅读