gpt4 book ai didi

c - getchar() 在尝试扫描输入时跳过第一个字符

转载 作者:行者123 更新时间:2023-11-30 21:05:47 25 4
gpt4 key购买 nike

我正在尝试扫描来自终端的输入,并且正在尝试扫描初始空白,但程序只是跳过它。我之前在另一个程序中尝试过使用此方法,但它在我的新程序中不起作用。请帮助!!!

#include <stdio.h>
#include <string.h>

#define ADMIN_PASS "ABC123"
#define MAX_ARR_LEN 20
#define debug

void getinput(char inp[], int n);
void password(char passUser[]);

int main(void)
{
char passUser[MAX_ARR_LEN+1];
int i=1;
while (i==1)
{
password(passUser);
printf("Try again?(1/0)>");
scanf("%d",&i);
if (i == 1)
printf("\n");
}
return 0;
}

void getinput(char inp[], int n)
{
scanf("%[^\n]c", &inp[n-1]);
#ifdef debug
printf("\nThe entered code in function>%s\n",inp);
printf("The 1st character of entered code in function>%c\n",inp[0]);
#endif
}

void password(char passUser[])
{
char admin[MAX_ARR_LEN+1] = ADMIN_PASS;
do
{
printf("\nPlease enter the Administrator password to Login:\n");
getchar();
getinput(passUser);
#ifdef debug
printf("\nThe input password in main is>%s\n", passUser);
printf("The 1st character in main is>%c\n", passUser[0]);
#endif
if (strcmp(passUser, admin) != 0)
{
printf("The password entered is incorrect, try again\n");
}
} while (!(strcmp(passUser, admin) == 0));
}

最佳答案

您应该使用 fgets(inp, sizeof(ADMIN_PASS), stdin) 传递字符串,如下所示:

#include <stdio.h>
#include <string.h>

#define ADMIN_PASS "ABC123"
#define MAX_ARR_LEN 20
#define debug

void getinput(char * inp);
void password(char * passUser);

int main(void)
{
char passUser[MAX_ARR_LEN+1];
int i=1;
while (i==1)
{
password(passUser);
printf("Try again?(1/0)>");
scanf("%d",&i);
if (i == 1)
printf("\n");
}
return 0;
}

void getinput(char * inp)
{
fgets(inp, sizeof(ADMIN_PASS), stdin);
#ifdef debug
printf("\nThe entered code in function>%s\n",inp);
printf("The 1st character of entered code in function>%c\n",inp[0]);
#endif
}

void password(char * passUser)
{
char admin[MAX_ARR_LEN+1] = ADMIN_PASS;
do
{
printf("\nPlease enter the Administrator password to Login:\n");
getinput(passUser);
#ifdef debug
printf("\nThe input password in main is>%s\n", passUser);
printf("The 1st character in main is>%c\n", passUser[0]);
#endif
if (strcmp(passUser, admin) != 0)
{
printf("The password entered is incorrect, try again\n");
}
} while (!(strcmp(passUser, admin) == 0));
}

我删除了 getchar() 和函数 getinput() 的第二个参数,因为它们没有用。

关于c - getchar() 在尝试扫描输入时跳过第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52664177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com