首页 > 解决方案 > 从另一个文件c ++访问变量值

问题描述

我正在做一些需要密码的事情。

现在我可以创建文件并在其中存储自定义用户输入,但我似乎无法在任何地方找到如何使用用户创建的值存储变量,并使其在下次程序启动时能够读取该文件并了解其价值。

#include "stdafx.h"
#include "string"
#include "iostream"
#include "fstream"
#include "windows.h"

using namespace std;

int main() {
string user;
string pass;
string entry;

std::ifstream f("test.txt");
if (f.fail()) {
    std::ofstream outfile("test.txt");

    cout << "Please make a username.\n";
    cin >> user;

    cout << "Please make a password.\n";
    cin >> pass;

    outfile << user << std::endl;
    outfile << pass << std::endl;

    outfile.close();

    cout << "Please restart.\n";
    int x = 3000;
    Sleep(x);
}

else {
    cout << "please enter username\n";
    cin >> entry;

    if (entry == user) {
        cout << "Welcome";
        int x = 3000;
        Sleep(x);
    }

    else if (entry != user) {
        cout << "Nope";
        int x = 3000;
        Sleep(x);
    }
}

return 0;

}

标签: c++visual-c++

解决方案


您还没有添加必要的代码来读取保存的用户名和密码。在else函数部分,添加

f >> user;
f >> pass;

作为前两行。

else {

    // Read the user name and password from the file.
    f >> user;
    f >> pass;

    cout << "please enter username\n";
    cin >> entry;

    if (entry == user) {
        cout << "Welcome";
        int x = 3000;
        Sleep(x);
    }

    else if (entry != user) {
        cout << "Nope";
        int x = 3000;
        Sleep(x);
    }
}

推荐阅读