#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <time.h>
usingnamespace 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 :)
#include <iostream>
#include <fstream>
usingnamespace 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;
}