我试图从“users.txt”文件验证用户名,邮件和密码,我试图使用fgets,但是当我运行它时,它无法识别信息,当我尝试打印实际验证的内容时,原来它从fgets函数中得到的字符串完全出乎意料。
来自users.txt的数据:
据我所知,fgets返回字符串,直到找到\ n字符或它到达文件末尾。 我从printf那里得到了什么:
jj123 jj123 jj123 robt robt robt rob111 (空值) (空)
代码: `
void login(bool is_logged_in)
{
printf("enter your name\n");
string name_session = GetString();
printf("enter your mail:\n");
string mail_session = GetString();
printf("enter your password:\n");
string password_session = GetString();
FILE *users_file;
char getstring[100];
users_file = fopen("users.txt", "r");
if (users_file != NULL)
{
while (feof(users_file) == 0)
{
//added this to check what I was actually getting from file
string text1 = fgets(getstring,100,users_file);
string text2 = fgets(getstring,100,users_file);
string text3 = fgets(getstring,100,users_file);
printf("%s",text1);
printf("%s",text2);
printf("%s",text3);
//3 times because the if statement is checking 3 strings
if ((fgets(getstring,100,users_file) == name_session ) &&
(fgets(getstring,100,users_file) == mail_session) &&
(fgets(getstring,100,users_file) == password_session))
{
is_logged_in = true;
fclose(users_file);
menu();
}
}
printf("You've failed your log in.\n");
fclose(users_file);
menu();
}
else
{
printf("¡¡ERROR!!: there's been a problem and the program will now exit.\n");
}
}
`
答案 0 :(得分:0)
使用fstream代替
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
string line;
ifstream file("users.txt");
if(!file){
cout<<"file do not exist!\n";
return 0;
}
while(getline(file,line)){
cout<<line<<endl;
}
}