简体   繁体   中英

Program for Password in C++

Password program not working....pls help....for right input also it says wrong password

#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();
}

I want to know why this password program not working....is their any other way

To be able to use strcmp() , you need to NUL-terminate pass . You also need to make sure that pass is large enough to accommodate the NUL.

As <conio.h> is in use, I'm assuming Windows is being used. For those who are interested, here is a start on the proper way to do this. I input a line as the password, ending when enter is pressed, and don't show asterisks, as they give away the length pretty easily.

//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

Of course there are things you can do to improve it (a hardcoded password string is never a good thing), and go ahead and do so if you wish, but the point is that it works as a basic password input system and has an easy-to-follow structure. You can still use the things you love when getting a password input, rather than going one character at a time and resorting to C strings and code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM