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



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

#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>%sn",inp);
printf("The 1st character of entered code in function>%cn",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>%sn", passUser);
printf("The 1st character in main is>%cn", passUser[0]);           
#endif
if (strcmp(passUser, admin) != 0)
{
printf("The password entered is incorrect, try againn");
}
} 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>%sn",inp);
printf("The 1st character of entered code in function>%cn",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>%sn", passUser);
printf("The 1st character in main is>%cn", passUser[0]);
#endif
if (strcmp(passUser, admin) != 0)
{
printf("The password entered is incorrect, try againn");
}
} while (!(strcmp(passUser, admin) == 0));
}

我删除了getchar()函数的第二个参数getinput()因为它们毫无用处。

最新更新