0

Hello Im coding a very basic password generator and I want to write the output of the loop to a file using ofstream. My idea was each time the loop runs output one vocal from the array abc. I don't know to to make it to work and obvs. there is a better way of doing it.

#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <fstream>


using namespace std;

int main(){

    srand(time(0));

    cout << "You'r PW is: \t" << endl;
    char abc [] {'A', 'a', 'B' ,'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', 'W', 'x', 'Y', 'y', 'Z', 'z'};

    for(int i = 0; i <15; i++){
        int randomNum =  rand() % 53;
        cout << abc[randomNum];
        ofstream fob;
        fob.open("contr.txt");
        fob << abc[randomNum];
    }
}

By the way, I am getting characters like ',' and '->' which isn't in my array.

Andy
  • 186
  • 1
  • 4
  • 23

3 Answers3

2

Have to move

ofstream fob;
fob.open("contr.txt");

out of loop. Now you rewrite file on every iteration.

KonK
  • 290
  • 1
  • 8
  • 2
    Indexing out of the bounds of the array is also a problem. Assuming all of the letters were in the array the number should be 52, but there are 2 letters missing. – Retired Ninja Feb 10 '15 at 20:40
1

The problem here is very simple and there are two solutions to it. What your program does is create and open a new stream to a file every iteration of the loop, but by default the ofstream overwrites the files it opens so you can either move the stream opening out of the loop(the better way) or add the flag ios::app as a second argument to the stream opener in order to append the content you're outputting.

docfed
  • 18
  • 1
  • 4
1

Additionally, you should be using int randomNum = rand() % 52;. to choose a number in the set {0, 1, 2, ... 51}, which will be one of all the possible indexes to your array assuming you forgot to put 'X' in your array.

Patch92
  • 1,054
  • 11
  • 12