How to print '*' while entering a password

I've created a program to input a password but while printing it it contains garbage value. What is the reason behind it and is there is any way to solve it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<string.h>

using namespace std;

int main()
{
	system("cls");
	char un[20],c,pass[20];
	int h;
	cout << "Username : ";
	ss:
	gets_s(un);
	h = strlen(un);
	for (int a = 0; a < h; ++a)
	{
		if (un[a] == ' ')
		{
			cout << "!!!Error : Do not use space for your username.\nEnter again : ";
			goto ss;
		}
	}
	int u;
	cout << "Password : ";
sss:
	u = 0;
	do
	{
		
		c=_getch();
		system("cls");
		cout << "Username : " << un << "\nPassword : ";
		for (int i = 0; i <=u; ++i)
			cout << "*";
		if (c == ' ')
		{
			system("cls");
			cout << "!!!Error : Do not use space for your password.\nEnter again : ";
			goto sss;
		}
		else
			pass[u]=c;
		++u;
	}while (c != 13);
//	system("cls");
	cout << "\nYour password : " ;
	cout << pass;
	_getch();
	return 0;
}
Does it prints correct password and bunch of garbage data immediately after?
Where do you ask for the password ?
One of your problems is that you're treating pass as if it is a c string when you feed it to cout and it is not. You have not nul-terminated it.

If you're using C++, you should use C++ strings. You should also be more descriptive with your variable names.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <string>
#include <conio.h>

int main()
{
    std::string user_name;
    bool user_name_obtained = false;

    while (!user_name_obtained)
    {
        std::cout << "Username: ";
        std::getline(std::cin, user_name);

        if (user_name.find(' ') != std::string::npos)
            std::cout << "!!!Error : No spaces allowed in your user name.\n";
        else
            user_name_obtained = true;
    }


    std::string password;
    bool password_obtained = false;

    while (!password_obtained)
    {
        std::cout << "Password: " << std::flush;

        int c;
        while (c = _getch(), c != ' ' && c != '\r')
        {
            password += char(c);
            std::cout << '*' << std::flush;
        }

        if (c == ' ')
        {
            password.clear();
            std::cout << "\n!!!Error : No spaces allowed in your password.\n";
        }
        else
            password_obtained = true;
    }

    std::cout << "\nUser name is " << user_name << '\n';
    std::cout << "Password is " << password << '\n';
}
Ok thanks
next time will take care of this
Last edited on
Topic archived. No new replies allowed.