Hello, I've only been working with C++ for less than a week and I have a problem. I've written a question class for a trivia game that works fine when I enter data from the keyboard but I want it to be able to get data from a text file.
The problem I am having is that when I open the file to add questions and answers the file keeps getting reset to the beginning of the file whereas I need each line to advance every time getline() is called in the program and getline() is called within different functions.
In short is there a way to pass a file name (or fstream object) as an argument to a function, have said function extract the data it needs and when the same function or another function that uses the file is called the data stream picks up where the other left off. Something like the following:
lets say textfile.txt contains:
What is the capital of Kazakhstan?
1 : Bishkek
2 : Astana
3 : Tashkent
4 : Ashgabat
1 2 3 4 5 6 7 8 9 10 11
|
int main()
{
ifstream myFile;
myFile.open("textfile.txt");
Question Q; //An instance of my question class
Q.getQuestion(myFile); //Stores a line of data in a C-string
Q.getAnswers(myFile); //Stores 4 lines in a string array using a for loop
Q.giveQuestion(); //Uses cout to give the question
Q.giveAnswers(); // Uses cout with a for loop to give the answers
return 0;
}
|
Whatever I do and I've tried a lot, getAnswers() always resets to the beginning of the file and my output is:
What is the capital of Kazakhstan?
What is the capital of Kazakhstan?
1 : Bishkek
2 : Astana
3 : Tashkent
Any help would be much appreciated you can see how this would be very problematic when multiple questions are part of the file.