c++ - 如何在 C++ 中读取和检查文件内容?
问题描述
我现在正在解决一个 C++ 问题,我可以在文件中输入一个存在的名称,然后程序检查相应的密码。我写的主要代码是这样的:
#include <iostream>
#include <fstream>
#include <ostream>
#include <string.h>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS 1
class user {
public:
int password;
char name[20];
};
int main()
{
user c;
char str[20];
int password;
int password2;
int password3;
ifstream fin("pwb.txt", ios::in);
cout << "please enter your username: " << endl;
cin >> str;
while (fin >> c.name >> c.password) {
if (strcmp(str, c.name) == 0) //login successfully
{
cout << "please enter your password: " << endl;
cin >> password;
if (c.password == password) {
cout << "Welcome to phone Organizer!\n" << endl;
break;
}
else if (c.password != password) {
cout << "Wrong password!" << endl;
cout << "enter again!: ";
cin >> password2;
if (c.password == password2) {
cout << "Welcome to phone Organizer!\n" << endl;
break;
}
else if (c.password != password2) {
cout << "Wrong password!" << endl;
cout << "enter again!: ";
cin >> password3;
{
if (c.password == password3) {
cout << "Welcome to phone Organizer!\n" << endl;
break;
}
else {
cout << "Wrong! Fail to login! " << endl; //here to quit the system!
return;
}
}
}
}
}
else if (strcmp(str, c.name) != 0) {
cout << "your password: ";
char fname[] = "pwb.txt";
ofstream fin2(fname, ios::app);
fin2 << '\n' << str << ' ';
cin >> password;
fin2 << password;
fin2.close();
cout << "Add successfully!";
cout << "Welcome to phone Organizer!\n" << endl;
break;
}
}
fin.close();
return 0;
}
并且 pwb.txt 文件中的内容是
快乐123456
伤心 234567
对不起 345678
不知道为什么一进入兴欣,程序就可以正常运行;但是当输入一个已经存在的Sad 或Sorry 时,程序总是不会检查现有的内容,而是在pwb.txt 文件中再存储一次Sad。我怎么解决这个问题?
解决方案
推荐阅读
- dictionary - ISR 的 GCC 映射文件地址与内存值不同
- javascript - 反应组件道具中的流泛型
- arrays - 迭代删除索引 0 的列表的 Grails3/groovy 错误
- iframe - 检测 iFrame 中对 srcdoc 的支持
- php - 如果电子邮件地址已存在,则在插入时编辑 MySQL 值
- c++ - 无法与 libnvcuvid.so 静态链接
- javascript - 切换组件上的类映射
- vb.net - vb.net 在 POST 中接收 json 数据,其中键有正斜杠
- c# - 用于匹配 HH:MM 和 HH:MM:SS 时间格式的正则表达式
- dart - 完成小部件动画后,在 Flutter 中运行一个函数