I have a method that should read in a file called "Fruitdictionary.txt" and then print out the contents (a list of strings)... but instead it prints out "0x7fff5fbff838".
Here is the code:
void Words::readdictionary(){
ifstream file_ptr1;
file_ptr1.open("fruitdictionary.txt", ifstream::in);
string temp;
while (file_ptr1>>temp){
dictionarylist.push_back(temp);
if (dictionarylist.size() == dictionarylist.capacity()) {
dictionarylist.resize(dictionarylist.capacity()+1);
}
}
cout << &dictionarylist << endl;
};
&dictionarylist
takes the address of your list and prints that .
Instead, do something like
std::copy(dictionarylist.begin(), dictionarylist.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
Or a loop
for (std::string const& s: dictionarylist)
std::cout << s << "\n";
PS: No need to resize your list (assuming
std::list
,
std::deque
,
std::vector
etc. was used). Standard library containers do memory management themselves, and push_back
will grow the allocated memory as required.
A slightly cleaned-up take:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
struct Words {
void readdictionary();
void printdictionary();
private:
std::vector<std::string> dictionarylist;
};
void Words::readdictionary(){
using namespace std;
ifstream file("fruitdictionary.txt");
dictionarylist.insert(
dictionarylist.end(),
istream_iterator<string>(file), {}
);
}
void Words::printdictionary(){
using namespace std;
copy(begin(dictionarylist), end(dictionarylist),
ostream_iterator<string>(cout, "\n"));
}
int main()
{
Words words;
words.readdictionary();
words.printdictionary();
}
I am assuming dictionarylist is vector you cannot print a vector like that in C++. You can print it this way
for(int i = 0; i < dictionarylist.size(); ++i) {
cout << dictionarylist[i] << endl;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.