I'm having to build a Hangman game and within the game I've developed a void function that will open the file and read the next text. The problem I'm having is it opens and reads the first file fine, but when it moves to the second line/word it crashes. The code in question is below and any help would be greatly appreciated.
Now I have it locally within the function this will still not read the second line. It reads the first line again as if it were the second line. Not sure how to keep the file open continually throughout the program so when it calls the function again it will start on line 2, then 3, etc...
char next is uninitialized before it is used in the while loop
And each time you will grab the same line, when you close the file and open it back up again you will start from the beginning, making your function read the first line and closing it.
Another note, using those char arrays to hold words is a bit iffy, use char* or even better, std::string
I don't know what way to keep the file open throughout the entire program so when the main function repeatedly calls the open_and_hide function it will continue where it left off if that makes sense.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
// This function will open a file and read the contents into a list
// The function takes a filename and a std::vector of type string
void ReadFile(std::string filename, std::vector<std::string>& WordList)
{
std::ifstream ifs(filename.c_str()); // Open the file
std::string temp; // We will read in each word to this string
while(ifs.good()) // While we can still read stuff
{
std::getline(ifs, temp); // Get each word from the file
if(temp == "") break; // If nothing is found exit the loop
WordList.push_back(temp); // Add the word to the list
}
ifs.close(); // Make sure to close the file after reading!
}
int main()
{
std::vector<std::string> Words; // Make a list for the words to go in
ReadFile("words.txt", Words); // Read a file into the list
// This is just a fancy for loop, called a "Range based for loop"
// I learned it today and want to put it in practice :)
// Just imagine for(i = 0; i < Words.size(); i++)
for(constauto& i : Words) std::cout << i << "\n"; // Print out the words
// Of course you can make an index, and as they complete them you can move onto the next word
unsignedint Index = 0;
std::string word = Words[Index];
// Play the game
// If they guessed it, go to the next word
Index++;
if(Index >= Words.size())
{
std::cout << "Thank you for playing!\n\n";
return 0;
}
}