-2

I know there are lots of questions with similar titles here, but no one seems to work for me. I have this kind of txt file:

tree pine
color blue
food pizza

and I want to store the items in a char* 2d vector, such as

vector<vector<char*>> data;
..
..
data[0][0] = tree
data[0][1] = pine
data[1][1] = blue
ecc

This is the code:

// parse configuration file
bool Configuration::fileParser(char* filename)
{
    vector<vector<char*>> data;
    fstream fin("data/setup.txt");
    string line;
    while (fin && getline(fin, line))
    {
        vector<char*> confLine;
        char* word = NULL;
        stringstream ss(line);
        while (ss && ss >> word)
        {
            confLine.push_back(word);
        }
        data.push_back(confLine);
    }
    storeData(data);
    return 0;
}

But when I run the code an exception is thrown.

Exception thrown: write access violation.

How can I solve this problem? Thank you

Swagging
  • 21
  • 1
  • 5

2 Answers2

1

You haven't allocated any memory into which the data can be written. You'd need something like char* word = new char[50];. But just use a std::string it is safer and easier.

Michael Albers
  • 3,603
  • 3
  • 19
  • 30
0

Disclaimer: I do not have a compiler on hand to test the following code with files, but it should work.

Here is a reference I used: Parse (split) a string in C++ using string delimiter (standard C++)

Discription: Basically the following code parses the passed in file line by line then assigns the first word and second word into the vector. Notice that I used string(s) in the example because I didn't want to think about memory management.

#pragma once
#include <vector>
#include <fstream>
#include <string>

void Configuration::fileParser(string fileName)
{
    vector<vector<string>> data;

    ifstream configFile(fileName);
    string line, token;
    string delimiter = " ";
    size_t pos;
    if (configFile.is_open())
    {
        int n = 0;
        while (getline(configFile, line))
        {
            if (!line || line == "")
                break; //added as a safety measure
            pos = 0;
            if ((pos = line.find(delimiter)) != string::npos)
            {
                token = line.substr(0, pos);
                data[n][0] = token; //add first word to vector
                line.erase(0, pos + delimiter.length());
            }
            if ((pos = line.find(delimiter)) != string::npos)
            {
                token = line.substr(0, pos);
                data[n][1] = token; //add second word to vector
                line.erase(0, pos + delimiter.length());
            }
            n++;
        }
    }
    storeData(data);
}