1
#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");

}

This Program is getting crashed in vs code but when I use getchar() instead of getch() or getche() all is working fine. Why it is not working with getch() and how it will run as I want user to insert a password and thus want to use getch() not getchar().

no ai please
  • 732
  • 3
  • 11
  • 24
  • Your users will not be running inside VSCode. That's the difference. Run it in a real cmd console and it should work with getch. – Tim Roberts Jun 25 '21 at 06:24

1 Answers1

1

First of all #define max generates a warning "macro redefinition", so change that.

The second problem is that getch() and getche do not convert the Enter key to 'newline' \n but to 'return' \r

The third problem is that instead of incrementing the pointers, you are incrementing what they point to.

Here is the corrected code:

#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");
}

Finally you should also check i does not exceed the array bounds. The strings seem long enough, but not for players who try to break the program.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56