2

我有一个方法应该读入一个名为“Fruitdictionary.txt”的文件,然后打印出内容(字符串列表)......但它打印出“0x7fff5fbff838”。

这是代码:

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;
};
4

2 回答 2

3

&dictionarylist获取您列表的地址并打印出来

相反,做类似的事情

std::copy(dictionarylist.begin(), dictionarylist.end(), 
      std::ostream_iterator<std::string>(std::cout, "\n"));

或者一个循环

for (std::string const& s: dictionarylist)
    std::cout << s << "\n";

PS:无需调整列表大小(假设使用了std::list,std::deque std::vector)。标准库容器自己进行内存管理,并push_back会根据需要增加分配的内存。

稍微清理一下:

#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();
}
于 2013-10-17T23:28:04.760 回答
0

我假设字典列表是向量,你不能在 C++ 中打印这样的向量。你可以这样打印

for(int i = 0; i < dictionarylist.size(); ++i) {
    cout << dictionarylist[i] << endl;
}
于 2013-10-17T23:59:36.810 回答