C ++中的密码程序

时间:2013-01-05 08:45:37

标签: c++

密码程序不工作....请帮助....对于正确的输入也说错了密码

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

void main()
{  
  clrscr();
  int ctr=0;
  int  o;
  char pass[5];

  cout<<"enter password";
  for(int i=0;i<5 && (o=getch())!=13  ;i++)
  {  
    pass[i]=o;

    putch('*');
  }

  ctr=strcmp(pass,"luck");
  cout<<ctr;
  if(ctr==0)
  {
    cout<<"welcome";
  }
  else
  {
    cout<<"wrong password";
  }
  getch();
}

我想知道为什么这个密码程序不起作用....是他们的任何其他方式

2 个答案:

答案 0 :(得分:6)

为了能够使用strcmp(),您需要NULL终止pass。您还需要确保pass足够大以容纳NULL。

答案 1 :(得分:0)

正在使用<conio.h>,我假设正在使用Windows。对于那些感兴趣的人,这是开始正确的方法来做到这一点。我输入一行作为密码,在按下enter时结束,并且不显示星号,因为它们很容易给出长度。

//stop echoing input completely
HANDLE inHandle = GetStdHandle(STD_INPUT_HANDLE); //get handle to input buffer
DWORD mode; //holds the console mode
GetConsoleMode(inHandle, &mode); //get the current console mode
SetConsoleMode(inHandle, mode & ~ENABLE_ECHO_INPUT); //disable echoing input

//read the password
std::string password; //holds our password
std::getline(std::cin, password); //reads a line from standard input to password

//compare it with the correct password
std::cout << (password == "luck" ? "Correct!\n" : "Wrong!\n"); //output result

//return console to original state
SetConsoleMode(inHandle, mode); //set the mode back to what it was when we got it

当然,你可以采取一些措施来改进它(一个硬编码的密码字符串永远不是一件好事),如果你愿意,可以继续这样做,但重点是它可以作为一个基本的密码输入系统和有一个易于遵循的结构。在获取密码时,您仍然可以使用您喜欢的东西,而不是一次只使用一个字符并使用C字符串和代码。