tags:

views:

130

answers:

3

Is this possible? The idea is typing a password and it being translated to asterisks on the fly- pretty much like a password field on HTML. I've written this code, but it converts the input AFTER the user presses enter, not while he/she is typing.

#include <stdio.h>
#include <string.h>

#include <iostream>

int main()
{
    char password[11]; int i, j;
    printf("Enter the password : ");
    gets(password);
    system("cls");
    int str_len = (int)strlen(password);
    printf("Enter the password : ");
    for(i = 0;i<2;i++)
    {
         printf(" ");
         for(j=0;j<str_len/2;j++)
         {
             printf("*");
         }
    }
    system("PAUSE>nul");
}
+4  A: 

I don't think it is possible using standard io. You need a library for more advanced text user interface like ncurses.

fschmitt
+2  A: 

It is not directly possible using standard C, no. You typically need to convince the terminal to go into "raw" mode, in which the program is able to read each character as it's typed, i.e. not requiring enter to pressed. In the raw mode, you can also often turn off any built-in echo in the terminal, and thus get the display of typed-in characters under program control.

It might be possible to convince a terminal to do these things by outputting various escape codes, but if that is within your scope or not is hard to tell. Also, it depends on the exact terminal (and thus platform) in use.

unwind
Which is why people use ncurses to handle all that automatically.
Martin York
+3  A: 

If you do want to get some extra points from the teacher, you could look into the function int getch() which does what you want. It is located in the header file conio.h.

Googling for getch should provide you with some info - MSDN and cplusplus.com are my favorite pages.

Default
Thanks, I'll check that out too. :)
arscariosus
Great, now I get it. Much thanks.
arscariosus
*But* keep in mind that conio.h isn't standard.
Matteo Italia
Yessir, sir Matteo. It is acceptable to use in our university though, so the new code should be accepted. I just created a do-while loop with counter that prints asterisk and places the input in the array's element as long as the input is not a backspace, spacebar or enter.
arscariosus