In: Computer Science
C or C++ program
Create a list of 5 things-to-do when you are bored (in the text file things.txt, one line each), where each thing is described as a string of characters of length in between 10 and 50.
Design a C program to read these things in (from stdin or by input redirection) and store them in the least memory possible (i.e., only the last byte in the storage for each string can be the null character).
After reading things in, your C program continues to accept input from the user, it ignores whatever the user enters but the return key, and for each return key it randomly chooses one out of the 5 things to print to the stdout.
Your C program iterates the process for ever until the user enters an EOF (which means by input redirection your program terminates at the end of file).
By randomly choosing a thing, it means you should try to make the probability distribution as evenly as possible to any one of the 5 things-to-do.
Any help is appreciated!!
Thank you!!
Hello, Student I hope you are doing good and well in lockdwon.
Here is implementation of your problem which randomly print one (1) things-to-do from a file which is written by user, I have tried my best to include comments as much as I can , still if you have any problem then please ask me in comment section, I am always happy to help.
program.cpp
#include<iostream>
#include<stdlib.h>
#include<fstream>
#include<time.h>
#include<vector>
using namespace std;
// main() Function implementation
int main()
{
string one_line;
vector<string> lines;
srand(time(0));
//input file which is in same folder where my program is.
ifstream file("things.txt");
//counting number of total lines in the file
// store the lines in the string vector
int num_of_lines=0;
while(getline(file,one_line))
{
num_of_lines++;
lines.push_back(one_line);
}
//generate a random number between 0 and will count of total lines
int rand_num=rand()%num_of_lines;
//fetching a random things-to-do for you!!
cout<<lines[rand_num]<<endl;
return 0;
}
And here is my input file things.txt
Brush
Mirzapur 2
Office work
Shooping
Mobile repair
Output : - I have 2 sample output which gave me both time different things-to-do .
Second Output : -
Explanation :-
1. First you need to save input file which will have 5 things-to-do in same program directory otherwise you can mention full directory where your file is.
2. I used ifstream to read that file.
3. I used srand() function with ‘time(NULL)’ that will give random one things-to-do.
4. I used getline() function to count total number of lines in file.
5.I used push_back() funtion to store lines in string vector.
6. Now generate a random line.
7. Finally I fetched the line index and matched with rand() function to give output .
I have explained everything and still you have any doubt then feel free to ask in comment.
Please upvote or hit that like,thumbs-up button, it really motivates me<3
Thank you!!!
Have a nice day:)