You are not allocating any memory for the std::string
variables that you are asking std::getline()
to read into. You are allocating arrays of string*
pointers that do not point at anything. You need to change your code to either:
keep using an array of pointers, but allocate the actual string
variables for them:
std::string ** mes;
if (amount == 0) {
...
mes = new string*[1];
mes[0] = new string; // <-- here
std::getline(*myfile, *mes[0]);
}
else {
...
mes = new string*[amount];
for (int i = 0; i < amount; ++i) {
mes = new string[amount]; // <-- here
}
for (int i = 0; i < amount; ++i) {
...
std::getline(*myfile, *mes[i]);
}
}
remove the unnecessary level of indirection to begin with:
std::string * mes;
if (amount == 0) {
...
mes = new string[1];
std::getline(*myfile, mes[0]);
}
else{
...
mes = new string[amount];
for (int i = 0; i < amount; ++i) {
...
std::getline(*myfile, mes[i]);
}
}
Wit that said, you should stop using raw arrays to begin with, and instead use std::vector
:
#include <vector>
protected:
std::vector<int> next;
std::vector<std::string> mes;
int amount;
message :: message(ifstream * myfile) {
*myfile >> amount;
if (amount == 0) {
next.resize(1);
mes.resize(1);
*myfile >> next[0];
std::getline(*myfile, mes[0]);
}
else {
next.resize(amount);
mes.resize(amount);
for (int i = 0; i < amount; ++i) {
*myfile >> next[i];
std::getline(*myfile, mes[i]);
}
}
}
Either way, you should consider getting rid of the redundant code for the amount == 0
case. Use a local variable and set it to 1 if amount
is 0, otherwise set it to the actual amount
, and then you can use a single code line to perform the allocations regardless of the amount
value:
message :: message(ifstream * myfile) {
*myfile >> amount;
int numElements = (amount == 0) ? 1 : amount;
next = new int[numElements];
mes = new string[numElements];
for (int i = 0; i < numElements; ++i) {
*myfile >> next[i];
getline(*myfile, mes[i]);
}
}
message :: message(ifstream * myfile) {
*myfile >> amount;
int numElements = (amount == 0) ? 1 : amount;
next.reserve(numElements);
mes.reserve(numElements);
for (int i = 0; i < numElements; ++i) {
int value;
*myfile >> value;
next.push_back(value);
std::string line;
std::getline(*myfile, line);
mes.push_back(line);
}
}