gpt4 book ai didi

c++ - 为什么两次使用 ifstream 对象会导致错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:39 25 4
gpt4 key购买 nike

我想输出一个词在文本中出现的次数,并输出包含该词的行,但是当我输出vector[*beg]时,我发现vector是空的!

我认为问题在于使用 ifstream &ifs 两次:

auto wordMap=setMap(ifs);
std::vector<std::string> vvector = read_to_vector(ifs);

如果我交换这两个语句,它会立即崩溃

我想知道问题出在哪里,如何解决。

#include <iostream>
#include<vector>
#include <fstream>
#include <string>
#include <set>
#include <map>
#include <sstream>
#include <memory>

std::vector<std::string> read_to_vector(std::ifstream &ifs)
{
std::string lines;
std::vector<std::string> sentences;
while (std::getline(ifs, lines))
{
sentences.push_back(lines);
}
return sentences;
}


std::map<std::string,std::set<size_t>> setMap(std::ifstream &ifs)
{
std::vector<std::string> word_vector = read_to_vector(ifs);
std::string lines, words;
std::map < std::string, std::set<size_t> > word_map;
for (size_t i = 0; i < word_vector.size(); i++)
{
//i is the current line_num
std::istringstream stream(word_vector[i]);
while (stream >> words)
{
word_map[words].insert(i);
}
}
return word_map;
}
void print(std::ifstream &ifs)
{
auto wordMap=setMap(ifs);
std::vector<std::string> vvector = read_to_vector(ifs);
std::string search;
std::cout << "please input the word that you wanna search" << "\n";
std::cin >> search;
auto findw = wordMap.find(search);
if (findw != wordMap.cend())
std::cout << search << " occurs " << findw->second.size()
<< " times : " << std::endl;
std::set<size_t> lineNum = findw->second;
//it is a set
auto beg = lineNum.begin();
while (beg != lineNum.end())
{
std::cout << *beg;
//std::cout<<vvector[*beg];
beg++;
}
for (auto c : vvector)
std::cout << c << std::endl;

if (vvector.empty())
std::cout << "vector is empty!";
//WTF!!! vector is empty!!!
}

int main()
{
std::ifstream ifs;
ifs.open("text.txt",std::ios::in);
print(ifs);
ifs.close();
}

最佳答案

当您第一次调用 read_to_vector 时(在 setMap 中)它会到达文件末尾,因此当您下次调用它时(在 print), vector 将为空。在读取 read_to_vector 中的行之前重置光标。将其更改为:

std::vector<std::string> read_to_vector(std::ifstream &ifs)
{
ifs.seekg (0, ifs.beg);//add this
std::string lines;
std::vector<std::string> sentences;
while (std::getline(ifs, lines))
{
sentences.push_back(lines);
}
return sentences;
}

建议

我认为最好读取一次文件然后传递 vector :

std::map<std::string,std::set<size_t>> setMap(std::vector<std::string> word_vector )
{
//std::vector<std::string> word_vector = read_to_vector(ifs);
std::string lines, words;
std::map < std::string, std::set<size_t> > word_map;
//some code
}

然后

void print(std::ifstream &ifs)
{
std::vector<std::string> vvector = read_to_vector(ifs);
auto wordMap=setMap(vvector);

// some code
}

关于c++ - 为什么两次使用 ifstream 对象会导致错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32086473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com