[英]reading in ifstream file in C++
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". 我有一种方法,应该读入一个名为“ Fruitdictionary.txt”的文件,然后打印出内容(字符串列表)...但是,它却打印出“ 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 . &dictionarylist
采用列表的地址, 并打印。
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). PS:无需调整列表大小(假设使用了
std::list
,
std::deque
,
std::vector
等)。 Standard library containers do memory management themselves, and push_back
will grow the allocated memory as required. 标准库容器自己进行内存管理,而
push_back
将根据需要增加分配的内存。
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++. 我假设dictionarylist是向量,您不能像在C ++中那样打印向量。 You can print it this way
你可以这样打印
for(int i = 0; i < dictionarylist.size(); ++i) {
cout << dictionarylist[i] << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.