正在输入到文本文件

Inputing to text file

本文关键字:文本 文件 输入      更新时间:2023-10-16

这是我的代码:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int would;
    string pass;
    cout << "Password Manager v.1" << endl << endl;
    cout << "What's the secret?" << endl;
    cin >> pass;
    if(pass == "youcantknowsorry"){
        cout << "Access granted." << endl << endl;
        cout << "Would you like to add a new password (1) or view your passwords? (2)" << endl;
        cin >> would;
        if(would == 1){
            ofstream myfile;
            myfile.open ("example.txt");
            myfile << "NewPassword" << endl; <--- HOW CAN I MAKE THAT INPUT?
            myfile.close();
        }
        if(would == 2){
            cout << "Your passwords will open in a text file.";
        }
    }
    return 0;
}

我正在尝试为自己编写一个密码管理器。我已经使用类似cout的方法成功地创建、打开并写入了一个文件。但是,我需要用户输入信息并将其保存在文件中。

让我们假设这只是读取输入并写入文件,而不是在纯文本文件中管理密码。你有

int would;
cin >> would;

string pass;
cin >> pass;

因此,您已经知道如何读取用户的输入。类似地,您可以从用户那里读取密码,并将其流式传输到文件:

string password;
cin >> password;
myfile << password << endl;

您需要if语句中的这段代码:

cin >> would;
if (would == 1)
{
    std::cin >> pass;
    std::ofstream("example.txt") << pass << std::endl;
}