Friday, July 31, 2009

I want a program to open one of three (or more) text files at random when it runs.?

assume the files are named File1.txt, File2.txt and File3.txt. I was thinking maybe i could get a random number from 1 to 3 and use that in


ifstream file;


file.open ("FileX.txt")





is there a way a can change the X?


If not then please help me find a way to do this.


I would like to be able to do this with any number of files (3 or 30 or 300) so i dont want to use a switch. The only thing i want to have to change in the code is the range of numbers it should randomly select from. knowning what i know about c++ (which admittedly is not a whole lot) im pretty sure there is a way to do this.

I want a program to open one of three (or more) text files at random when it runs.?
Why not store the file names in a String array and have the random number used an as index, whatever it picks is the string that gets returned to open the file.
Reply:You can do this with a regular batch file. Create a file called launch.bat or whatever and add this to it:





@echo off


set /A maxfile = 4


set /A filenum = %random% %% %maxfile% + 1


File%filenum%.txt





Change maxfile to your maximum file number and run it. The maxfile variable is currently set to 4 so it will open a random file between File1.txt and File4.txt.








***UPDATED***





A batch file is just a regular text file, you run them as you would any other program i.e. there's no C++ involved. Just create a text file called launch.bat (or whatever you want to call it), copy that text into it and then run it as you would an exe or any other file (it needs to be in the same directory as all of your text files).





If you really do want to do it in C/C++ then this code will do the same thing. The key is the system() function, which is what you use to launch another application or file:





#include %26lt;stdio.h%26gt;


#include %26lt;time.h%26gt;


#include %26lt;stdlib.h%26gt;





const int maxfile = 4;





void main()


{


char command[32];





// initialize random number generator


srand((unsigned int)time(0));





// pick a random number


int filenum = rand() % maxfile + 1;





// create the filename string


sprintf(command, "File%i.txt", filenum);





// tell DOS to launch it i.e. open the text file


system(command);


}





*** UPDATED ONE LAST TIME*** :)





No probs, if you need any further clarification then feel free to email me.

flower pots

No comments:

Post a Comment