簡體   English   中英

使用帶有fstream的地圖進行Segfault

[英]Segfault using a map with fstream

我正在嘗試從文件中讀取文本,並同時跟蹤文本的內容。 如果將未出現的單詞插入地圖並初始化為1。如果已經看到(在地圖內存在),則僅增加該值。

如果我取消了調用[]運算符的操作,則文件的讀取工作正常。 為了確認讀取文件成功,我將第一個文件的內容輸出到一個輸出文件中。

因此,將鍵/值添加到地圖時會發生問題。 似乎我的代碼在第二次進入while循環時出現段錯誤。

這是一個用作單詞計數器的簡單類,以及一個處理文件打開,對象創建和文件讀取的主要方法。

#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();

}

就目前而言,您的代碼有許多錯誤甚至無法編譯。 修復這些問題並添加一個成員函數以查看單詞計數器收集的統計信息之后,我得到的結果與預期的一樣(並且沒有段錯誤或類似的東西)。

#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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM