如何解决使用 getch 和 getche 时程序崩溃
#include <stdio.h>
#include <conio.h>
#define max 100
void compare(char *name,char* input);
int main()
{
int i=0;
char name[max]="santosh";
char input[max];
printf("enter the password\n");
while((input[i]=getchar())!='\n'){
i++;
}
input[i]='\0';
compare(name,input);
return 0;
}
void compare(char *name,char* input){
while((*name==*input)&&(*name!='\0'&&*input != '\0')){
*name++;
*input++;
}
if(*name=='\0'&&*input=='\0')
printf("Correct Password");
else
printf("Incorrect Password");
}
这个程序在 vs 代码中崩溃了,但是当我使用 getchar() 而不是 getch() 或 getche() 时,一切正常。 为什么它不能使用 getch() 以及它如何运行,因为我希望用户插入密码并因此想要使用 getch() 而不是 getchar()。
解决方法
首先,#define max
会生成一个警告“宏重定义”,因此请更改它。
第二个问题是 getch()
和 getche
不会将 Enter 键转换为 'newline' \n
而是转换为 'return' {{1} }
第三个问题是,不是递增指针,而是递增它们指向的内容。
这是更正后的代码:
\r
最后你还应该检查 #include <stdio.h>
#include <conio.h>
#define MAXX 100 // fixed macro name collision
void compare(char *name,char* input);
int main(void) // corrected definition
{
int i = 0;
char name[MAXX] = "santosh";
char input[MAXX];
printf("enter the password\n");
while((input[i] = getche()) != '\r') { // fixed '\n' check
i++;
}
input[i] = '\0';
compare(name,input);
return 0;
}
void compare(char *name,char* input){
while(*name == *input && *name != '\0' && *input != '\0') {
name++; // fixed pointer increment
input++; // fixed pointer increment
}
if(*name == '\0' && *input == '\0')
printf("Correct Password\n");
else
printf("Incorrect Password\n");
}
没有超出数组边界。字符串看起来足够长,但对于试图破坏程序的玩家来说却不是。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。