Strange logical error

Okay, So I am writing a program that requires lots of coding. After completing a fraction of it, I am stuck for a stupid logical error.

While entering the password if the user presses 'enter', The loop is supposed to break. But it still continues to take input. Please Help!!!!!!

ps: if you somehow require to full code, I will provide it.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  int getPassword(){
        char password[20],test[20];
                 int i=0;
                 do{
                    test[i]=getch();

                    i++;
                    if(test[i]==13)
                        break;
                   else{
                    password[i]=test[i];
                    cout<<"*";
                   }
                 }while(i<20);
                if(PasswordChecker(0,password))
                return 1;
else
    return 0;
}
1
2
3
4
test[i]=getch();
i++;
if(test[i]==13)
     break;


The fault lies in this little block of code.

Let's say i = 0.
You get input for test[0].
You increment i, so i = 1.
You test if test[1] is equal to 13.
test[1] is not initialized yet, so it's going to have some insanely large negative number.
To fix your code, change it to look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int getPassword(){
     char password[20],test[20];
     int i=0;
     do{
          test[i]=getch();
          if(test[i]==13)
               break;
          else{
               password[i]=test[i];
               cout<<"*";
          }
          i++; // Move i to this location in your loop.
      }while(i<20);
      if(PasswordChecker(0,password))
           return 1;
      else
      return 0;
}
Last edited on
Thank you so much.
Topic archived. No new replies allowed.