R.O.T
R.O.T

Reputation: 21

How to display asterisks for password input only after two consecutive colons?

I want to read input from user. After the user typed the sequence ::, the rest of the input should be asterisks.

For example: let's say user typed: Alex::vn800. On the screen, the output should be: Alex::*****.

I have a function that reads input from user and display * on screen, but I didn't managed to use it in a middle of reading line.

I tried to manipulate functions getchar() and scanf() to stop reading line after detecting a sequence of ::, and then call the function but nothing worked.

What can I do?

Update: Hey! thanks for the answers. I fainlly solved the problem by using the library conio.h - like in any other simple get-password code, just that I saprated it for cases according to what I want the screen will show and not just '*' for any case.

Upvotes: 1

Views: 353

Answers (1)

hornobster
hornobster

Reputation: 736

If it's not strictly necessary to have both username and password in the same line, I would suggest simply getting the username first and then using the getpass() function, like here.

I've tried ataman's method, but it didn't work on OSX 10.9.

Here's a modified version, following goldPseudo's approach:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int readChar;
    int status = 0;
    int semicolonCount = 0;

    system ("/bin/stty raw"); // disable buffering and other stuff
    while ((readChar = getchar()) && (readChar != 13 /* ENTER keycode */))
    {
        if (status == 0)
        {
            printf("%c", readChar);

            if (readChar == ':')
            {
                semicolonCount++;
            } else {
                semicolonCount = 0;
            }

            if (semicolonCount == 2)
            {
                status = 1;
            }
        } else {
            printf("*");
        }
    }
    printf("\r\n"); // print new line
    system ("/bin/stty cooked"); // reenable buffering, might not be the original mode the terminal was in

    return 0;
}

The problem with this approach is that, since you are in "raw mode", special characters, like BACKSPACE, ENTER, Ctrl+D and even Ctrl+C, are not processed. You would have to implement the behaviour for those characters yourself.

Upvotes: 1

Related Questions