Open a random file

I am trying to write a program to choose a file at random from a number of files (named "recipe1.txt", "recipe2.txt", ect) and display it's contents.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <time.h>

using namespace std;

int number_of_files = 0;

int main(){
	cout << "Enter 's' to select random recipe:";
	char start;
	cin >> start;
	if(start == 's'){
		srand(time(NULL));
		string line;
		int k;
		int number_of_files = 4;
		char filename[16];
		sprintf(filename,"recipe%i.txt",rand()%(number_of_files + 1));
		// cout<<filename<<endl;

		ifstream myfile(filename);
		while (getline(myfile,line)){
			cout << line << '\n';
		}

		myfile.close();

	}
	return 0;
}


My main problem would be with the file name, I'm not sure "recipe%i.txt" will do what I want. What should I use in that place?

Also, if anybody happens to know, how would I open a .txt file written in notepad? I can't seem to open .txt files that were not written with a c++ program.

Randomise a number to say between 1 to 5, use a switch statement to check what number was generated and set a string variable to the file name of your choice for each switch case.

Once the variable has been set to the file name you can then just open it in the usual manner and do what you need to do :)




Something like this..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

#include <iostream>
#include <fstream>
using namespace std;

int main()
{

	fstream externalFile;
	string fileName;
	int choice;

	// think of a number, in this example
	// 0 or 1
	choice = (rand() % 2);	// 0 - 1

	switch (choice)
	{
		case	0:
			fileName = "file1.txt";
		break;
		case	1:
			fileName = "file2.txt";
		break;
	}

	externalFile.open(fileName, fstream::in);
	if (externalFile.is_open())
	{
		// do your stuff.

		// now close
		externalFile.close();
	}
	else
		cout << "We have a problem opening the file.";
	
	return 0;
}
Topic archived. No new replies allowed.