C++ 密码程序屏蔽字符有什么问题?

C++ 密码程序屏蔽字符有什么问题?,c++,c++11,C++,C++11,我写了一个程序来显示密码,就像我们通常看到的那样,但我不知道它有什么问题,因为它在输入3个字符后就停止了。。。。请帮忙 #include <iostream> #include<string.h> #include<conio.h> using namespace std; int main(){ char* pass=new char[20]; int i=0; cout<<"\n\n Pass : "; while(pass[i]!='\0

我写了一个程序来显示密码,就像我们通常看到的那样,但我不知道它有什么问题,因为它在输入3个字符后就停止了。。。。请帮忙

#include <iostream>
#include<string.h>
#include<conio.h>

using namespace std;

int main(){
char* pass=new char[20];
int i=0;
cout<<"\n\n Pass : ";
while(pass[i]!='\0')
{
    pass[i]=getch();
    i++;
    cout<<"*";

}

cout<<"\n\n";

if(strcmp(pass,"Vivek")==0)
{
    cout<<"Access Granted! "<<endl;
}
else
{
    cout<<"Access Denied!";
}
return 0;
}
所做的更改已在摘要部分中描述

//New code based on the discussions below

#include <iostream>
#include<string.h>
#include<conio.h>

using namespace std;

int main()
{
char pass[20];
int i=0;
cout<<"\n\n Pass : ";
do
{
    pass[i]=getch();
    i++;
    cout<<"*";

}while(pass[i-1]!='\0');
cout<<"\n\n";

if(strcmp(pass,"Vivek")==0)
{
    cout<<"Access Granted! "<<endl;
}
else
{
    cout<<"Access Denied!";
}
return 0;
}

在循环中,在将任何值放入插槽之前,先检查插槽中的“\0”

根据您的初始化,您尚未初始化pass[0]或pass数组中的任何插槽

该值可能是零,也可能是2016年。在使用变量(包括数组)之前,应始终初始化变量

您需要重新考虑循环将如何终止。例如,当用户按Enter键时,getch返回的值是多少?是“\0”吗

此外,为了防止缓冲区溢出,用户输入30个字符,应该使用C++ STD::string类型。如果坚持使用C样式字符数组,则输入循环应检查缓冲区溢出


您还应该处理退格的情况,并且不要忘记缓冲区下溢检查。

您需要发布代码。您可能希望将while循环更改为do{}while循环。@cornstales仍然无法正常工作。不需要动态分配char数组。charpass[20];在这里可以正常工作。传递指向的数组的内容没有初始化,所以对传递[i]所做的任何测试都是没有意义的。你提到你改变了循环做了一件事。。。while循环,但尚未显示代码。如果测试在i++之后查看pass[i],它仍然在测试未初始化的内存。相反,请看pass[i-1],因为这是输入的地方。谢谢,长官,但它仍然变为unfine循环
while(pass[i]!='\0')
{
    pass[i]=getch();
    i++;
    cout<<"*";
}
while (pass[0] != '\0')