我必须将字母数字密码放入文本文件中

I have to put an alphanumeric password in a text file

代码如下:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
        
const char alphanum[] = "0123456789!@#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int string_length = sizeof(alphanum)-1;

int main()
{
    system("Color 0A");
    int n;
    cout<<"Quanto deve essere lunga la password? ";     // Here it's asking me the length of the password
    cin>>n;
    srand(time(0));
    for(int i=0; i<n; i++)
        cout << alphanum[rand() % string_length];
    ofstream fout("password.txt");
            
    cout <<""<<endl;             // Here I need the variable to write the password in the text file
    fout.close();
                
    fout<<"Grazie comunque"<<endl;
    return 0;
}

你需要把写密码的代码移到循环里面

ofstream fout("password.txt");
for(int i=0; i<n; i++)
{
    char password_char = alphanum[rand() % string_length];
    cout << password_char;
    fout << password_char;
}
fout << endl;
fout.close();

与您写入 cout.

的代码完全相同