首页 > 解决方案 > 如何在 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。我怎么解决这个问题?

标签: c++

解决方案


推荐阅读