Reputation: 11
I'm learning c++ and I have a problem with a segmentation fault. In my project I want to read from a File into a 2d Vector of char.
The Vector is std::vector<std::vector<char>> gamearea;
void Structure::readFile(const std::string filename)
{
std::ifstream file(filename.c_str());
if (!file.is_open())
{
std::cerr << "Error opening file: " << filename << std::endl;
exit(1);
}
std::string line;
int i = 0;
while (true)
{
std::getline(file, line);
if (file.eof())
{
break;
}
for (size_t j = 0; j< line.length(); j++)
{
gamearea[i].push_back(line[j]);
}
i++;
}
}
This is my read file function and the debugger (I use gdb) says by push_back
is a segmentation fault.
Can someone help me? I can't find the problem.
Upvotes: 1
Views: 1231
Reputation: 35440
Here is an example of properly reading in and updating your vector, given that it is empty:
void Structure::readFile(const std::string filename)
{
std::ifstream file(filename.c_str());
if (!file.is_open()) {
std::cerr << "Error opening file: " << filename << std::endl;
return;
std::string line;
while (std::getline(file, line))
gamearea.push_back(std::vector<char>(line.begin(), line.end()));
}
Note we don't need to test for eof()
. Also, all we need to do is call push_back
an entire string of data using the two argument std::vector constructor that takes two iterators.
Upvotes: 0
Reputation: 4763
You need to first push back into the first vector a std::vector<char>
because by default the gamearea vector is empty, so when accessing gamearea[i] you end up accessing out of bounds (since gamearea has 0 elements inside it)
void Structure::readFile(const std::string filename)
{
std::ifstream file(filename.c_str());
if (!file.is_open()) {
std::cerr << "Error opening file: " << filename << std::endl; exit(1);
}
std::string line; int i = 0;
while (true) {
std::getline(file, line);
if (file.eof()) { break; }
// NOTICE HERE
// We add a new vector to the empty vector
std::vector<char> curArea;
gamearea.push_back(curArea);
for (size_t j = 0; j< line.length(); j++) {
gamearea[i].push_back(line[j]);
}
i++;
}
}
Upvotes: 3