簡體   English   中英

C ++中的密碼程序

[英]Program for Password in C++

密碼程序不起作用.... pls幫助....對於正確的輸入,它也說錯了密碼

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

我想知道為什么此密碼程序無法正常工作。

為了能夠使用strcmp() ,您需要使用NUL終止pass 您還需要確保pass足夠大以容納NUL。

由於正在使用<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字符串和代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM