I have the following code to read data from a comma-delimited file. This works as long as each field is present. However, if I get a line like 1234,fname,lname,,01,0,123456789 then the program dies on the null at the time of the push_back. How can I convert that null to a space?
Code:
void initialize_vector(std::vector<record*>& vec)
{
char detailline[100];
std::string sdetailline;
char * s; // element placeholder
char * dup_str;
std::string tempstring;
int colcount = 0;
int daysapart = 0;
//assign tmp as pointer to record struct
record* tmp;
std::ifstream fin;
fin.open ("zz.csv", std::ios::in);
if(fin.fail())
{
throw read_exception();
}
while(!fin.fail() && !fin.eof())
{
fin.getline(detailline, 100, '\n');
if (detailline[0] != NULL)
{
dup_str = strdup(detailline); // make (malloc) copy of input string
s = dup_str; // first element is at start
strtok(s, ","); // first element is now NUL-terminated
colcount++;
tmp = new record;
tempstring = s;
tmp->corp = static_cast<std::string>(s);
while (s != NULL)
{
s = strtok(NULL, ","); // move to next
if (colcount == 1)
{
tmp->lastname = static_cast<std::string>(s);
}
else if (colcount == 2)
{
tmp->firstname = static_cast<std::string>(s);
}
else if (colcount == 3)
{
tmp->lwi = static_cast<std::string>(s);
}
else if (colcount == 4)
{
tmp->grade = static_cast<std::string>(s);
}
else if (colcount == 5)
{
tmp->tanf = static_cast<std::string>(s);
}
else if (colcount == 6)
{
tmp->ssn = static_cast<std::string>(s);
}
colcount++;
}
colcount = 0;
//std::cout << tmp->lastname<<std::endl;
vec.push_back(tmp);
free(dup_str); // release copy - you should have made copies of any required elements before doing this !
}
}
fin.close();
}