我试图扫描来自终端的输入,并且试图扫描初始空白,但是程序只是跳过了它。我以前尝试在其他程序中使用此方法,但在新程序中不起作用。请帮助!!!
#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));
}
答案 0 :(得分: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()
的第二个参数导致它们无用。