简体   繁体   中英

Segfault using a map with fstream

I am trying to read text from a file, and while doing so keeping track of the contents of the text. If a word that hasn't been seen before it is inserted into the map and initialized to 1. If it has been seen (exists within the map), then the value is simply incremented.

If I remove the action of calling the [] operator, then the reading of the file works fine. I output the contents of the first file into an output file for the sake of confirming that reading a file is a success.

So, an issue occurs when adding keys/values to the map. It seems that my code segfaults upon entering the while loop for the second time.

Here is a simple class which acts as the word counter, and a main method which handles the opening of the files, creation of an object, and the reading of the file.

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

}

As it stands right now, your code has a number of errors that prevent it from even compiling. After fixing those and adding a member function to see the statistics collected by the word counter, I'm getting results about as I'd expect (and no segfaults, or anything similar).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM