I am making a text based adventure game, where I read from a text file containing all of the rooms, descriptions, etc. The code compiles but when ran it does cause a segmentation fault (core dumped).
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct Room {
string title;
string description;
string exits;
int exitIndices[4] = {0};
};
int main(int argc, char* argv[]) {
if (argc < 2) {
cout << "Usage: ./mud <roomfile>\n";
return 1;
}
ifstream roomFile(argv[1]);
if (!roomFile) {
cout << "Failed to open the room file.\n";
return 1;
}
// Step 1: Count the number of rooms
string line;
int roomCount = 0;
while (getline(roomFile, line)) {
if (line == "~") {
roomCount++;
}
}
roomCount /= 3;
// Step 2: Create an array of Room objects
Room* rooms = new Room[roomCount];
// Step 3: Read and populate the Room objects from the file
roomFile.clear();
roomFile.seekg(0, ios::beg);
int currentRoom = -1;
int lineNum = 0;
while (getline(roomFile, line)) {
if (line == "~") {
currentRoom++;
lineNum = 0;
} else {
switch (lineNum) {
case 0:
rooms[currentRoom].title = line;
break;
case 1:
rooms[currentRoom].description = line;
break;
case 2:
rooms[currentRoom].exits = line;
size_t pos = 0;
int exitIndex = 0;
while ((pos = line.find(" ")) != string::npos) {
string exitStr = line.substr(0, pos);
stringstream ss(exitStr);
line.erase(0, pos + 1);
int exitNumb;
ss >> exitNumb;
rooms[currentRoom].exitIndices[exitIndex++] = exitNumb;
}
if (!line.empty()) {
stringstream ss(line);
int exitNumb;
ss >> exitNumb;
rooms[currentRoom].exitIndices[exitIndex++] = exitNumb;
}
break;
}
lineNum++;
}
// Uncomment the following line to debug the reading of the room file
// cout << "Line " << lineNum << " of room " << currentRoom << ": " << line << endl;
}
// Step 4: Print out the rooms
for (int i = 0; i < roomCount; i++) {
cout << "Room " << i << ":\n";
cout << "Title: " << rooms[i].title << endl;
cout << "Description: " << rooms[i].description << endl;
cout << "Exits: " << rooms[i].exits << endl;
cout << "Exit Indices: ";
for (int j = 0; j < 4; j++) {
cout << rooms[i].exitIndices[j] << " ";
}
cout << endl;
}
delete[] rooms;
return 0;
}
I have tried redoing my while(getline)(roomFile,line)) a couple of times but I don't believe this to be the issue anymore