首页 > 解决方案 > 使用 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()。

标签: arrayscstringwhile-loopgetch

解决方案


首先#define max生成一个警告“宏重新定义”,所以改变它。

第二个问题是,getch()不要getcheEnter键转换为“换行符”\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不超过数组边界。字符串似乎足够长,但对于试图破坏程序的玩家来说不是。


推荐阅读