171k views
3 votes
Write a program that allows the user to type in any one-line question and then answers that question. The program will not really pay any attention to the question, but will simply read the question line and discard all that it reads. It always gives one of the following answers:I'm not sure, but I think you will find the answer in Chapter #N.

That's a good question.
If I were you, I would not worry about such things.
That question has puzzled philosophers for centuries.
I don't know. I'm just a machine.
Think about it and the answer will come to you.
I used to know the answer to that question, but I've forgotten it.
The answer can be found in a secret place in the woods.
These answers are stored in a file (one answer per line), and your program simply reads the next answer from the file and writes it out to the console as the answer to the question. After your program has read the entire file, it simply closes the file, reopens the file, and starts down the list of answers again.
Whenever your program outputs the first answer, it should replace the two symbols #N with a random number between 1 and 18 (including the possibility of 1 and 18). In order to choose a random number between 1 and 18, your program should call the rand() function (remember to call srand() at the beginning of the program to seed the rand() function). Also, have the program prompt the user for the name of the answer file.

User Stanpol
by
4.2k points

1 Answer

2 votes

Solution and Explanation:

//Header files

#include<iostream>

#include<string>

#include<fstream>

using namespace std;

int main()

{

fstream fin;

char str[]="";

string question;

char filename[20];

char choice;

string answer;

//seed for random number

unsigned seed=0;

srand(seed);

cout<<"Enter your file name : ";

cin>>filename;

cout<<endl;

//if file not exist then gives message

//reading file

do

{

fin.open(filename,ios::in);

if(!fin)

{

cout<<"couldnot find the file...";

std::system("pause");

return 0;

}

while(!fin.fail())

{

cout<<endl<<"Enter your quesion"<<endl;

fflush(stdin);

getline(cin,question);

answer="";

char ch;

while((ch=fin.get())!='\\'&&!fin.fail())

{

//reading line

answer+=ch;

if(ch=='#')

{

int randNum=1+rand()%18;

answer +=randNum+'0';

ch=fin.get();

}

}

cout<<answer<<endl;

}

fin.close();

cout<<"Do you want to continue (Y/y to continue) :";

cin>>choice;

}while(choice=='y'||choice=='Y');

//To pause the output

system("pause");

return 0;

}//end of main..

User Jduprey
by
3.9k points