使用带有fstream的地图的segfault
Segfault using a map with fstream
我正在尝试从文件中读取文本,并在这样做时跟踪文本的内容。如果一个在将其插入地图并初始化为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();
}
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- 基于多个条件处理地图中的所有元素
- C++中带有List类的迭代器Segfault
- 在C++中将矢量转换为嵌套地图
- 使用Vulkan hpp vk::enumerateInstanceVersion()会导致segfault
- 替换基于地图的所有引用
- 如何区分地图中的 0 和 false?
- 地图计数确实很重要,或者只是检查是否存在
- 如何从地图中删除矢量对象
- 是否有任何C++功能可以对地图进行排序?
- 如何使用 std::variant 打印地图键/值?
- 从矢量或地图中删除共享指针
- 在 c++ 中,有一种方法可以创建一个包含地图作为值的树状地图?
- 无限嵌套具有变体的地图
- C++一会儿循环读到地图上 2 行?
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 如何检查变量是否是C++中的地图?
- 使用带有fstream的地图的segfault
- 在c++地图访问上的segfault