'I have to put an alphanumeric password in a text file

Here's the code:

#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;
}


Solution 1:[1]

You need to move the password writing code inside the loop

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();

Exactly the same as your code that writes to cout.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 john