Victor Laurentiu
Victor Laurentiu

Reputation: 145

How to delete an already written character in C++ console

I'm trying to make a C++ program to read a password. I made the program to cout *, not the characters I write but my problem is when I want to delete character because they're wrong.
Example: My constant password is 12345
If I enter 1235 the program will show **** and I have to delete the last character. It's simple to remove it from the string but I want the last * to disappear from the console just as it happens when you introduce you windows password.
Is it possible? If it is, can someone explain how?

Upvotes: 8

Views: 32261

Answers (6)

I faced the same thing recently, using the \b was** moving the cursor backward** but it was not deleting the char (or * ). I realize after that the next character you enter after \b is gonna replace the (character to be deleted). So, I came up with something like this

printf(“\b \b”);

using the space key after \b will replace the character to be deleted and again using the \b will take you one position back again (to the position where was incorrect character was, but this time the character will not be there) This way your output will look smooth. hope it will be helpful to you

Upvotes: 0

deeiip
deeiip

Reputation: 3379

Sipmly write the '\b' character to stdout std::cout<<"\b". If you are using cpp or printf("\b") for pure C

Upvotes: 0

user3057544
user3057544

Reputation: 868

When I am writting to console using putch function ( from conio.h ) to simulate backspace key simple

std::cout << '\b';

or

printf("\b ");

not works I have to write:

cout << '\b' << " " << '\b';

or

putch('\b');
putch(' ');
putch('\b');

Upvotes: 2

Pruthvi Chitrala
Pruthvi Chitrala

Reputation: 184

printf("\b ");

This statement surely works because after the cursor goes one character back and space given in above printf statement will overwrite the printed character on console output.

Upvotes: 5

mxsscott
mxsscott

Reputation: 403

Outputting the backspace character '\b' may help to move the output point back.

Specifically, outputting the string "\b \b" should blank out the last character output.

Upvotes: 13

atamanroman
atamanroman

Reputation: 11808

Try backspace \b or erase the whole line and print it again.

Upvotes: 0

Related Questions