n00bpr0grammer
n00bpr0grammer

Reputation: 9

Backspace key not working in C++ code

I am trying to make a C++ program that accepts a username and password from the user and matches it to the ones that are already stored in the variables. For the password, I am using the * (asterisk) character to appear instead of the actual characters for privacy.

#include <iostream.h>
#include <conio.h>
#include <dos.h>
#include <string.h>

void main(void) {
    clrscr();

    gotoxy(10,10);
    cout << "Username: ";
    gotoxy(10,12);
    cout << "Password: ";

    char name1[10] = {"Apple"};
    char name2[10];
    char pass1[10] = {"Orange"};
    char pass2[10] = {""};

    gotoxy(23,10);
    cin >> name2;
    gotoxy(23,12);
    cout << pass2;

    int i = 0;
    char ch;

    while ((ch = getch()) != '\r') {
        putch('*');
        pass2[i] = ch;
        i++;
    }

    if (strcmp(name1, name2) == 0 && strcmp(pass1, pass2) == 0) {
        clrscr();
        gotoxy(40,10);
        cout << "YES!!!";
    } else {
        clrscr();
        gotoxy(40,10);
        cout << "NO!!!";
    }
}

The problem is when I try to use the backspace key on the keyboard, I doesn't delete the character, instead it adds more characters to the end of it. I can make it work by importing the C language's string.h library. But is there any way I can make it work by using the libraries that are already defined in the code without having to use the string.h library.

Upvotes: 0

Views: 2361

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

The problem is when I try to use the backspace key on the keyboard, I doesn't delete the character, instead it adds more characters to the end of it

Correct! When you use the backspace key, it actually generates a backspace character (ASCII 0x8). The backspace key doesn't "delete characters"; you only think it does, because software is normally written to look out for backspace characters and behave specially when it encounters them. In this case, the writer of that software is you!

You'll need to look at the value of ch, see whether it's a backspace character … and, if so, "do the needful" (only you can tell what this is).

I can make it work by importing the C language's string.h library.

Including string.h has nothing to do with it and will have no effect on this.

Upvotes: 1

Lenigod
Lenigod

Reputation: 153

Backspace is considered a "non-printing character", which is where this behavior is coming from. You'll likely have to handle it as you've already thought out in the question.

you can click here for a quick glance at this and other non-printing characters. http://www.physics.udel.edu/~watson/scen103/ascii.html

Upvotes: 0

Related Questions