c++ - a simple getch() and strcmp problem -


i have simple problem gets input user using function checks if input 'equal' "password". however, strcmp never return desired value, , culprit somewhere in loop uses getch() take each character separately , add them character array. found out having printf display character array. if type in pass word, function display pass word ". have no idea on why closing double quote , whitespace included in array right after word typed in. idea? here's code. thanks.

#include <stdio.h> #include <iostream> #include <conio.h> #include <string.h>  int validateuser();  int main() {    for(int x = 0;x<2;x++)    {          if(validateuser())          {                 system("cls");              printf("\n\n\t\t** welcome **"); break;           }         else                              {                 system("cls");              printf("\n\n\t\tintruder alert!");              system("cls");           }    }        system("pause>nul");     return 0; }  int validateuser() {     char password[9];     char validate[] = "pass word";     int ctr = 0, c;     printf("enter password : ");          {         c = getch();         if(c == 32)         {              printf(" ");              password[ctr] = c;         }          if(c != 13 && c != 8 && c != 32 )         {           printf("*");           password[ctr] = c;         }         c++;         }while(c != 13);      return (!strcmp(password, validate)); } 

  • your char array password not have terminating null char.
  • you need ensure don't stuff more 8 char password
  • also c++ should ctr++

.

do {  // stuff char password.  ctr++;  }while(c != 13 && ctr <8);  password[ctr] = 0; 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -