gpt4 book ai didi

c - 不接受密码

转载 作者:太空宇宙 更新时间:2023-11-04 02:19:14 24 4
gpt4 key购买 nike

在 lesson2() 下面的代码中,我使用了密码进入函数,但是当我进入函数时,它没有输入密码,而是说密码不正确。不输入密码,我的意思是说我已经使用了 gets,但它正在等待我输入密码。请不要告诉我不要使用 gets!

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<dos.h>
int mistakes=0,mistakes_length,len;
char temp[100];
void lesson1(void);
void lesson2(void);
void result(void);
void main(void)
{
int choice;
clrscr();
printf("Enter a lesson number to practise:1-10 \n");
scanf("%d",&choice);
switch(choice)
{
case 1:
lesson1();
result();
break;
case 2:
lesson2();
result();
break;
default:
printf("You did not entered a valid choice program quitting..\n");
exit(0);
}
getch();
}
void lesson1(void)
{
int i;
char str1[100]="testing the typing tutor if it works";
mistakes_length=5;
clrscr();
gotoxy(25,2);
puts("Welcome to lesson 1");
puts(str1);
len=strlen(str1);
for(i=0;i<len;i++)
{
temp[i]=getche();
if(strncmpi(&str1[i],&temp[i],1))//does not match
{
mistakes++;
sound(100);
delay(1000);
nosound();

}
}
getch();
}
void result(void)
{
printf("Your statsistics are as under:\nYou performed this lesson with %d mistakes\n",mistakes);
if(mistakes>=mistakes_length)
{
printf("\n Your typing is very bad");//allow anything to be typed with any mistake in lesson 1

}
if(mistakes>3&&mistakes<5)
{
printf("Bad!,You need to practise this excercise more\n");
}
if(mistakes>=1&&mistakes<=3)
{
printf("Good!you can still do better\n");
}
if(mistakes==0)
{
printf("Excellent!You are qualified for the next lesson\n");
printf("The next lessons password is \n\t\t\t:12345");
}
}

void lesson2(void)
{
char password[]="12345",str2[]="My name is khan and i am not a criminal";
int i;
mistakes=0,mistakes_length=0,
printf("Enter password:\n");
gets(temp);
if(strcmp(temp,password))
{
gotoxy(20,25);
printf("Wrong Password,Program Quitting.\n");
getch();
exit(1);
}
gotoxy(25,25);
printf("Password Accpted!");
getch();
clrscr();
gotoxy(25,2);
printf("Welcome to lesson 2\n");
printf("Type the text shown below:\n");
puts(str2);
len=strlen(str2);
for(i=0;i<len;i++)
{
temp[i]=getche();
if(strncmp(&str2[i],&temp[i],1));
{
mistakes++;
}

}
getch();
}

我觉得是scanf和get在一起出问题了!

最佳答案

您的问题是,在调用 gets() 之前,您调用了 scanf("%d",&choice);(在 main() 中)。问题是控制台输入是面向行的。这意味着虽然您只是在等待输入数字,但用户必须输入以换行符 结尾的完整行。 %d 格式说明符仅消耗数字字符,将行的其余部分留在缓冲区中以供下一次控制台输入调用使用;在这种情况下是 gets(),它在缓冲区中看到 换行符 并返回一个空字符串,而不等待进一步的输入。

解决方案:

scanf("%d",&choice);
while(getchar() != '\n' ) { /*no nothing*/}

关于c - 不接受密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3379902/

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