[英]How do I take input from user as a password and compare it with the data in the file in c++
我正在 C++ 中制作一個項目,我需要在其中制作一個登錄系統。 我寫了下面的代碼,但是當我們在login()
function 中運行 case 2 時,我無法弄清楚為什么密碼不匹配。
核心理念:
首先,我們需要注冊用戶名和密碼,這是在login()
function 的案例 1 中完成的。 然后,用戶可以通過他的用戶名和密碼訪問信息。
面臨的問題:
當我嘗試使用已注冊用戶的用戶名和密碼時,密碼不匹配。 我檢查了存儲的密碼並通過將它們打印到控制台來輸入密碼,它們是相同的。 但是,當我們使用==
運算符比較兩者時,它會給出錯誤的結果。 誰能解釋為什么?
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<conio.h>
using namespace std;
int login(void);
int main(void)
{
cout<<"Login system\n";
int d;
d = login();
if(d)
cout<<"Access granted!!"<<endl;
else
cout<<"Access denied!!"<<endl;
}
int login(void)
{
system("CLS");
cout<<"\n\n\n";
string username, password;
fstream file;
int choice;
again:
cout<<"1.Add new user\n2.login\n";
cin>>choice;
switch(choice)
{
case 1:
{
file.open("Login details.txt", ios :: app);
cout<<"Enter new username and password\n";
cin>>username;
cin>>password;
file<<username<<"\t\t";
file<<password<<endl;
return 1;
break;
}
case 2:
{
file.open("Login details.txt", ios :: in);
string tempname, temp_pass, k;
char temp_pas[100];
int p = 0;
cout<<"Enter your username and password\n";
cin>>tempname;
do
{
temp_pas[p] = getch();
if(temp_pas[p] != '\r')
cout<<"*";
p++;
}while(temp_pas[p - 1] != '\r');
cout<<endl;
for(int i = 0; i < p; i++)
{
temp_pass += temp_pas[i];
}
while(file)
{
file>>username;
file>>password;
cout<<q<<endl<<w<<endl;
if(tempname == username && temp_pass == password)
{
cout<<"access granted\n";
return 1;
}
}
cout<<"Invalid username or password\n";
return 0;
break;
}
default
{
cout<<"Choose a valid option"<<endl;
goto again;
}
}
}
你讓這一切變得困難,只需簡單地將 id 和密碼作為字符串保存到文件中,然后讀取文件,然后檢查使用 string.compare() function
將 for 循環從:for (int i = 0; i < p; i++) 更改為:for (int i = 0; i < p-1; i++)
編譯器當前正在讀取 \r 作為輸入密碼的最后一個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.