here i have written a code to accept a password entered by the user after he have entered his username,i have written a small code using do while statement to print out the star every time when ever user enter any character,& the loop terminates when the user enters a '!'. but it surprised me w开发者_StackOverflowhen i see the password entered by the user,& the string length of the entered password,THE STRING length always comes out to be 21,in my case,& the output of password is a combination of the password entered by the user & the username......what's going on??????
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main()
{
char username[15],password[15];
int i=0;
cout<<"\nEnter your USERNAME:";
cin>>username;
cout<<"\nenter your password:";
do
{
password[i]=getch();
if(password[i]=='!')break;
cout<<"*";
i++;
}while(i<15);
cout<<"\n\nthe password entered was"<<password<<"\nthe length of the password is" <<strlen(password);
getch();
return 0;
}
You have defined:
char password[15];
And as per your loop, it continues until i
is equal to 14
(i.e, 15th character). So there is no space for NULL termination. Let it be like this:
char password[16];
Now, just after the loop, add:
password[i] = 0;
i
will be at 15
if user didn't enter '!' and if he did, it will be replaced with NULL
character. I think this is the easiest fix. If you don't want the '!' to be replaced, place i++;
before break;
You are not terminating your string with a NULL.
do
{
password[i]=getch();
if(password[i]=='!') break;
cout<<"*";-
i++;
}while(i<15);
if (i < 15) password[i] = '\0';
A C string must be terminated by the special character '\0'
, which is not the case with your password/username. You have to set the i+1
th character to '\0'
:
password[i]=getch();
password[i+1] = '\0';
Also you have to consider that your password buffer must also contain this string, so you have just space for 14 characters if you define char password[15];
so your loop can just go to 14.
You read 15 characters but you never write a '\0' in the string so it's not terminated.
It is
#include <iostream>
#include <string>
please correct that. If your compiler does not know these files, then your compiler is not any good.
Then, why don't you use std::string instead if char-arrays?
That would avoid any of these errors.
What you do here, is a mix of c and c++.
精彩评论