使用带有fstream的地图的segfault

Segfault using a map with fstream

本文关键字:地图 segfault fstream      更新时间:2023-10-16

我正在尝试从文件中读取文本,并在这样做时跟踪文本的内容。如果一个在将其插入地图并初始化为1之前没有看到的单词(如果已看到它(在地图中存在),则该值简单地增加了。

如果我删除调用[]运算符的动作,则文件的读数正常。我将第一个文件的内容输出到输出文件中,以确认读取文件是成功的。

因此,当在地图上添加键/值时会出现问题。,我的代码第二次输入WALE循环时似乎是segfault。

这是一个简单的类,充当单词计数器,是一种处理文件打开,创建对象的主要方法,读取文件。

#include <map>
#include <string>
#include <fstream>
using namespace std;
class WordCounter
{
public:
    map<string, int> words;
    WordCounter operator[] (const std::string &s)
    {
        ++words[s]; 
              // If we put a breakpoint here in GDB, then we can print out the value of words with GDB.
              // We will see that we sucessfully entered the first string.
              // But, the next time we enter the while loop we crash.
        }
    }
};
int main()
{
    WordCounter wc; 
    ifstream inFile;
    ofstream outFile;
    string word;
    inFile.open("input.txt");
    outFile.open("output.txt");
    while(inFile>>word)
    {
        outFile << word << " ";
        wc[word]; // This line seems to cause a segfault 
    }
    inFile.close();
    outFile.close();
}

现在,您的代码有许多错误,可以防止其编译。修复了这些内容并添加成员函数以查看单词计数器收集的统计信息后,我会根据我的期望获得结果(没有segfaults或类似的内容)。

#include <map>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
class WordCounter
{
public:
    map<string, int> words;
    void operator[] (const std::string &s)
    {
        ++words[s]; 
    }
    void show() {
        for (auto const& p : words) {
            std::cout << p.first << " : " << p.second << "n";
        }
    }
};
int main()
{
    WordCounter wc; 
    ifstream inFile("input.txt");
    string word;
    while(inFile>>word)
    {
        wc[word]; 
    }
    wc.show();
}