I'm in the middle of creating a simple program with C++ (11).
My issue is that function called "loadRoomsFile()" is reading text from a file to char pointer array and then return it.
I want to convert it to a string so I have used string constructor with parameter of *char array.
All tests are showing, buffer also shows correct data but when calling string(loadRoomsFile()) I get bad_alloc exception and program stops running. Can anyone help me?
char *loadRoomsFile() {
fstream roomsFile;
char *buffer;
// helper
int i = 0;
cout << "TEST 1" << endl;
roomsFile.open("rooms.txt");
cout << "TEST 2" << endl;
if(roomsFile.is_open()) {
cout << "TEST 3" << endl;
roomsFile.seekg(0, ios::end);
cout << "TEST 4" << endl;
buffer = new char[roomsFile.tellg()];
cout << "TEST 5" << endl;
roomsFile.seekg(0, ios::beg);
cout << "TEST 6" << endl;
while(!roomsFile.eof()) {
cout << "TEST WHILE" << endl;
buffer[i] = roomsFile.get();
i++;
}
cout << "TEST 7" << endl;
}
roomsFile.close();
cout << "TEST 8" << endl;
buffer[i] = '\0';
cout << "TEST 9" << endl;
cout << buffer << endl;
return buffer;
}
/*
* GENERAL FUNCTION
*/
int main() {
// Variables
int currentSection; // option choosed in Main Menu
int revert = true; // used for going back in time XD
//string roomsData; // used for storage of data from file
vector<Room> rooms;
cout << "----------------------------------------------------------------" << endl;
cout << "Conference Room Manager ver. 0.1" << endl;
cout << "Component 1/4, Bartosz Kubacki/Bartlomiej Urbanek" << endl;
cout << "----------------------------------------------------------------" << endl;
cout << endl;
// load all data from files
cout << "TEST MAIN" << endl;
string roomsData(loadRoomsFile());
return 0;
}
Thanks!