I've written a custom string class called DSString, with a private member char* data. I'm trying to parse lines from a csv file, adding each word found in the line of a file to a std::set of DSString objects. I call getline to read in a line from the file into a char* buffer, then call strtok to get a word. However, the while loop below does not work; my debugger tells me that upon reaching that line of code, it calls my constructor in DSString.h with parameter NULL, then the program ends.
int main (int argc, char ** argv) {
ifstream input;
input.open(argv1);
int reviewLinesCtr = 0;
char line[16000];
set <DSString>positiveWordSet;
while (input.getline(line,16000)) {
if (reviewLinesCtr == 10) break;
//Push review to positive set
DSString word = strtok(line, " ");
while (word != nullptr) { //Program ends abruptly here
positiveWordSet.insert(word);
word = strtok(nullptr, " ");
}
}
reviewLinesCtr++;
}
return 0;
}
DSString only has private members char *data
and int size
.
Here is the relevant code in DSString:
DSString::DSString(const char* param) { //This is the constructor being passed, param = NULL, which crashes the program.
data = new char[strlen(param) + 1];
this->size = strlen(param) + 1;
strcpy(data, param);
}
DSString& DSString::operator= (const char* source) {
if (data != nullptr) {
delete[] data;
}
data = new char[strlen(source + 1)];
size = strlen(source) + 1;
strcpy(data, source);
return *this;
}
bool DSString::operator!= (const DSString& rhs) const {
if (strcmp(this->data, rhs.data) != 0) {
return true;
}
else {
return false;
}
}
This is part of a project for college, so we are required to implement the custom DSString class. Otherwise I would not use it and instead use std::string. We also cannot use a char* anywhere in the program except for a buffer to read from the file. Why is this constructor being called and given NULL as a parameter when I try to start going through this while loop? And how can I fix it?
I apologize if this is a repeat question, I have been searching the internet for some time and have not found anything that helps explain what's going on here. Any help would be appreciated.