【问题标题】:Program is getting crashed when using getch and getche使用 getch 和 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 一起使用。

标签: arrays c string while-loop 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 没有超出数组边界。字符串似乎足够长,但不适合试图破坏程序的玩家。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多