I tried this because it seemed like a good exercise for me.
I came up with 2 methods:
The easy way.
a) Fill a character array with all 26 letters then use random_shuffle() to "randomize" the order of the elements.
b) Write all 26 letters to the file.
#include <iostream>
#include <fstream>
#include <cstdlib>// for rand()
#include<ctime>
#include<algorithm>// for random_shuffle()
usingnamespace std;
int main()
{
char ltrs[26];// an array to hold all 26 letters
srand((unsigned)time(0));// seed random # generator
for(int i=0; i<26; ++i)
ltrs[i] = 'a' + rand()%26;// assign letters in alphabetic order
random_shuffle( ltrs, ltrs+26);// shuffle the letters in the array randomly
fstream fs("test.txt", fstream::out);
if( fs.is_open() )
{
for(int i=0; i<26; ++i)// write all the letters to the file.
fs << ltrs[i];
fs.close();
}
else
cout << "could not open file.";
cout << endl;
return 0;
}
The hard way.
a)Generate a character randomly.
b) Search the file for this character.
c) If the character was not found then write the character to the file, otherwise generate another random character and try again.
The program below includes extra stuff for counting the # of tries to insert the characters.