You should replace
!infile.eof() with
infile anywhere it occurs in your code. Lines 27, 31, and 58.
You can completely get rid of the do-while loop.
While it's not bad to close the file explicitly, there's really no need since the destructor will do it for you.
You should use
getline on line 48.
On to the problem:
Let me restate it so I (and you) can be sure I understand. You want your program to prompt a user for a question. You then want your program to present the user with an answer based on the answers listed in your file for that specific question. The organization of the file is such that lines that indicate questions do not begin with a space and those that should be answers do begin with a space. Your problem is that you are unsure how to associate the questions/answers after reading them from the file?
Where you are going wrong:
The questions and answers must be read in, in their entirety, before you start asking for user input.
There is, in your code, no association between the questions and answers array (ie. there's no way to tell which answers belong to which questions.)
I would begin by defining a data structure:
1 2 3 4 5 6
|
struct QnA
{
string question ;
string answers[5] ;
unsigned n_answers ;
};
| |
I use an array for answers, because I don't know if you're familiar with the std::vector type which would be a much better fit. Of course, you should modify the size of answers to something that is appropriate for your program.
Then you may use an array of QnA:
QnA QandA[100] ;
which you populate with the information from your file.
When that's done, you ask your user for a question. loop through QandA to find it and randomly choose one of the answers.