逐行读取文本文件留下矢量空

时间:2017-05-03 09:16:53

标签: c++ vector text-files ifstream

我正在尝试阅读如下文本文件:

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],我会收到错误“矢量下标超出范围”

我做错了什么?

2 个答案:

答案 0 :(得分:4)

unsigned line_count = count(istreambuf_iterator<char>(myfile), istreambuf_iterator<char>(), '\n');

这里您使用了流中的所有数据。之后,没有剩余数据。因此,getline次呼叫无需循环播放。

由于它是一个文件流,你可以&#34;寻找&#34;回到文件的开头并再次开始使用所有数据:

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()稍后会给你相同的信息。也许你可以删除那些代码并以这种方式解决问题。

答案 1 :(得分:1)

我不明白为什么你不能先读行,然后计算它们。

while (getline(myfile, line)){
    v_names.push_back(line);
}

auto line_count = v_names.size();

然后再次,因为.size()没有走开,只要你知道你有多少名字,就打电话给它。

SIDE注意:计算'\n'的数量不能保证一直有效,因为最后一行不一定以换行符结束。

相关问题