Ofstream trouble,我该如何解决这个问题?

ofstream trouble, how do i resolve this?

本文关键字:解决 问题 trouble 何解决 Ofstream      更新时间:2023-10-16

我在一个包含单词作为键的映射上迭代,每个单词都有一堆分配的数字存储在vector<int>中,指示在哪一行找到它们。我在。txt文件中输出该信息时遇到了麻烦。

在文件中出现足够多的单词垃圾后,程序崩溃。

经过一些简短的测试,我发现错误发生在明显的地方,即输出最终信息到。txt文件时。

在谷歌了一下之后,唯一相关的信息片段是有人简短地说不应该在循环中使用ofstream。我猜这可能会导致溢出?也许是什么东西没被冲走?

那么哪里出了问题,为什么?我该如何解决这个问题?

//FINAL OUTPUT TO A FILE, CREATING A NEW .txt FILE
ofstream filehandle;
filehandle.open("result.txt",ios::out);
if( filehandle.is_open() )
{
     for(map<string, vector<int> >::const_iterator a = line_num_by_word.begin();a!=line_num_by_word.end();++a)
    {
        filehandle << "The word "  << """ << a->first << """ <<  " is present on: n";
        vector<int>::const_iterator int_vec_c_it = a->second.begin();
        while( int_vec_c_it != a->second.end() )
        {
            vector<int>::const_iterator in_front_of_it = int_vec_c_it+1;
            //count the number of times
            int counter = 1;
            while( *(int_vec_c_it)==*(in_front_of_it) )
            {
                ++counter;
                ++in_front_of_it;
            }
            filehandle << " line " << *(int_vec_c_it) << "-" << counter << " times ";
            int_vec_c_it = in_front_of_it;
        }
        filehandle << "n";
    }
}else cout << "no output" <<endl;

当a->second()在end()之前是1时,it_front_of_it是end()。然后在while语句中解引用它。

while( *(int_vec_c_it)==*(in_front_of_it) )