I'm working on an assignment that wants me to read a file into an vector of char pointers in order to eventually find and count the ten most common words. I'm still working on putting it into my char* vector. At first, my output only spits out a bunch of weird characters, and then jumbles up the rest of the file. As I'm trying to read in the US Constitution, it takes a while to compile, and ends up way longer than it should be. Here's my code:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
string word;//temp to hold one word string read by ifstream
vector<char*> doc_words;//will hold each char address read by ifstream
ifstream my_file;//file reader
//reads text into doc_words
my_file.open("UnitedStatesConstitution.txt");
if (my_file.is_open())
{
while (my_file >> word)
{
for (int i = 0; i < word.length(); i++)
{
doc_words.push_back(&word[i]);
}
}
my_file.close();
}
//reading out array on char at a time
for (int i = 0; i < doc_words.size(); i++)
{
cout << doc_words[i];
}
system("pause");
return 0;
}
The problem that you make is when you read word by word of a file using my_file >> word, you are basically accessing the same string again and again which always has the same memory location. Now suppose at the start at the memory location of word[1] you have an "a" and in the next word you have "e" as the second letter, then the pointer that you have stored for the earlier word will point to "e". Therefore, you get garbled letters in your output. You can make do with this problem if you simply convert your vector of char pointers to just a vector of char and ido doc_words.push_back(word[i]); I guess this should work.
Thanks for your response! For this assignment, it specifically states that I need to use a vector of char*, otherwise I would definitely be using a vector or char. Is there a way that I could work with what I have now without having to create an object for each item of memory in my vector?
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
string word;//temp to hold one word string read by ifstream
vector<char*> doc_words;//will hold each char address read by ifstream
ifstream my_file;//file reader
unsigned last_pos=0;
//reads text into doc_words
my_file.open("UnitedStatesConstitution.txt");
if (my_file.is_open())
{
string temp;
while (my_file >> temp)
{
word.append(temp);
word.push_back(" ");
for (unsigned i = last_pos; i < word.length(); i++)
{
doc_words.push_back(&word[i]);
}
last_pos = word.length();
}
my_file.close();
}
//reading out array on char at a time
for (int i = 0; i < doc_words.size(); i++)
{
cout << *(doc_words[i]);
}
system("pause");
return 0;
}