当我输入用户名和密码并输出程序时:
密码错误!!!密码错误!!!密码错误!!!密码错误!!!密码错误!!!密码错误!!!
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
typedef struct data{
char user[50], pass[50];
} data;
using namespace std;
int main(){
ifstream fi;
ofstream fo;
data log;
char finduser[50];
char findpass[50];
string regis= "";
cout << "registered?[Yes/No]";
cin >> regis;
if(regis == "No"){
cout << "Register Panel";
fo.open("log.txt", ios::binary | ios::app);
cout << "\nUsername: ";cin >> log.user;
cout << "Password: ";cin >> log.pass;
fo.write((char *) &log, sizeof(log));
fo.close();
goto login;
}else{
login:
cout << "\nLogin Panel";
cout << "\nUsername: ";
cin >> finduser;
cout << "Password: ";
cin >> findpass;
fi.open("log.txt", ios::binary);
while(fi.read((char *) &log, sizeof(log))){
if(strcmp(log.user, finduser) == 0 && (strcmp(log.pass,findpass) == 0)){
cout << "\nLogin Succes";
}else{
cout << "Wrong Password!!!";
}
}
fi.close();
}
getchar();
return 0;
}
我的C ++代码有什么问题?
我尝试了很多不同的方法但仍然出错:
registered?[Yes/No]No
Register Panel
Username: aaa
Password: aaa
Login Panel
Username: aaa
Password: aaa
Wrong Password!!!Wrong Password!!!Wrong Password!!!Wrong Password!!!Wrong Password!!!Wrong Password!!!
Login Succes
------------------
(program exited with code: 0)
Press return to continue
答案 0 :(得分:0)
您正在检查log.txt中的多行。并为每行打印Wrong Password
以表示不匹配。
你应该这样做:
bool success = false;
while(fi.read((char *) &log, sizeof(log)))
{
if(strcmp(log.user, finduser) == 0 && (strcmp(log.pass,findpass) == 0))
{
cout << "\nLogin Succes";
success = true;
break;
}
}
fi.close();
if(!success)
{
cout<<"Wrong Password!!!";
}
您需要检查整个文件以匹配。并显示输出一次。
希望这会有所帮助