我正在尝试读取一个文本文件,如下所示:
Gate
People
Crab
Motorbike
我的代码是:
string line;
vector<string> v_names;
ifstream myfile("c:/temp/test.txt");
if (! myfile.is_open()) {
cout << "Failed to open" << endl;
}
else {
cout << "Opened OK" << endl;
}
myfile.unsetf(ios_base::skipws);
unsigned line_count = count(istreambuf_iterator<char>(myfile), istreambuf_iterator<char>(), '\n');
while (getline(myfile, line)){
v_names.push_back(line);
}
如果我想通过
v_names.size()
获得向量的大小,它将返回0。如果调用v_names[0]
,则会出现错误“向量下标超出范围”我究竟做错了什么?
最佳答案
unsigned line_count = count(istreambuf_iterator<char>(myfile), istreambuf_iterator<char>(), '\n');
在这里,您消耗了流中的所有数据。之后,没有剩余数据。因此,没有任何循环可以通过
getline
调用进行。由于它是文件流,因此您可以“搜索”回文件的开头并再次开始使用所有数据:
unsigned line_count = count(
istreambuf_iterator<char>(myfile),
istreambuf_iterator<char>(),
'\n'
);
myfile.seek(0, std::ios_base::beg);
myfile.clear();
while (getline(myfile, line)) {
v_names.push_back(line);
}
但是,您有一个问题,就是您的
line_count
方法被破坏了。最后一行不一定以'\n'
结尾,让您离开一个。提醒你,下午指出,反算行数似乎毫无意义,因为
v_names.size()
稍后会为您提供相同的信息。也许您可以删除该代码并以这种方式解决问题。