使用 getch 和 getche 时程序崩溃

Posted

技术标签:

【中文标题】使用 getch 和 getche 时程序崩溃【英文标题】:Program is getting crashed when using getch and getche 【发布时间】:2021-09-08 13:23:41 【问题描述】:
#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()。

【问题讨论】:

您的用户不会在 VSCode 中运行。这就是区别。在真正的 cmd 控制台中运行它,它应该可以与 getch 一起使用。 【参考方案1】:

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

第二个问题是getch()getche没有将Enter键转换为'newline'\n而是'return'\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 没有超出数组边界。字符串似乎足够长,但不适合试图破坏程序的玩家。

【讨论】:

以上是关于使用 getch 和 getche 时程序崩溃的主要内容,如果未能解决你的问题,请参考以下文章

等效于 Mac/Linux 崩溃的 Windows getch()

C中创建的窗口崩溃的原因

使用 getch() 进行标准输入时输入 EOF 表示法

c语言中的getch与getchar 有啥区别?

_getch 似乎暂停了我的程序

getch与getchar区别