arrays - 使用 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键转换为“换行符”\n
而是“返回”\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");
}
最后,您还应该检查i
不超过数组边界。字符串似乎足够长,但对于试图破坏程序的玩家来说不是。
推荐阅读
- c# - EditForm 验证未将无效类应用于自定义组件
- c# - Linq2Db“BeginTransactionAsync”中的 System.NullReferenceException
- python - 如何对 pandas GroupBy 对象中的组进行排序?
- angular - RXJS - 仅在调度终止后调用 select
- python - 循环后无法取消无限 Tkinter(嵌套)
- python - 如何使用 openFDA API 进行分页
- python - AttributeError:模块“torch.nn”没有属性“ReflectionPad3d”
- reactjs - Reactjs MUIDataTable 隐藏数据
- pine-script - Pinescript - 全局变量的历史参考在函数中返回意外结果
- javascript - 如何检查特定字母的输入值及其计数