My assignment is to create a program that reads a text file and displays a list of the top ten most common words in it. To do this, I read the file into a vector and then play around with the vector to get the output I want. My problem lies in the instructions I am given:
NOTE: We could store our words as just strings, but we'd like you to gain some experience with pointers and memory allocation. Thus, we require that you store your words in string pointers and then store these pointers in a vector. The focus of this lab is to get comfortable with working with pointers.
I am doing just fine storing all of the text into a vector, and I don't really know what they mean by this.
My problem is that I get pointers and references mixed up pretty badly. I have gone about placing *'s and &'s on every variable and in every combination I can imagine and am not getting anywhere. The textbook is no help and I haven't found the documentation very applicable. Here is the code in question:
vector<string> v_add() //adds words to the vector
{
vector<string> words;
ifstream in_file;
in_file.open("C:\\Users\\Michael\\Desktop\\test.txt");
//--------------------------------------------
//check for failure
if(in_file.fail()) //This is left over from when I was debugging opening the file. I'll clean it up later.
{
cout << "Failed to open file.";
system("pause");
exit(EXIT_FAILURE);
}
//--------------------------------------------
string current_word;
if(in_file >> current_word )
{
getline(in_file, current_word);
words.push_back(current_word);
}
in_file.close();
return words;
}
It works like a charm, just not in the way the assignment wants. Help is always appreciated.
Now by the above code I assume you already know how to read lines from a file into strings and store them into a vector. The only thing that remains, then, is to convert them to pointers so you can push them onto the vector. How would you do that?
(But think carefully; remember that objects are destructed when they go out of scope.)
On line 7, you would need to the address-of operator. You can't simply assign a string to a string*; you need to get the address of it first.
However, while it would compile, it would not work properly because you are storing a pointer to a string that is local to the function, and when the function ends that variable disappears. That leaves the pointer pointing to bad memory; I think you'll need to use dynamic allocation to get around that.