I've have been struggling with trying to figure out an issue I am getting if the last line of the column in a csv file is empty. What seems to happen is if the last column is empty, it either skips it or give incorrect data (not really sure yet). Been working on this for a few days now and am now looking for any ideas on resolving it.
My code that reads the csv file gathers the data and places it into a 2D vector. Here's the code for the first part:
bool valid = false;
std::string file = ParamsD.bulkUploadFile; //"Files\\BulkUpload.csv"
std::vector<std::vector <std::string>> buffer; //buffer to store all the data read from the file
std::ifstream configFile;
configFile.exceptions(std::ifstream::badbit);
//Read the CSV file into a buffer
try
{
std::string line;
configFile.open(file.c_str(), std::ifstream::in);
while(configFile.is_open())
{
if (!std::getline(configFile, line))
break;
std::istringstream ss(line);
std::vector<std::string> record;
while (ss)
{
std::string s;
if (!std::getline(ss, s, ','))
break;
record.push_back(s);
}
buffer.push_back(record);
}
}
catch (std::ifstream::failure e)
{
throw e;
return false;
}
The second part of the function reads the buffer and then places the information into a struct which then is called for in other parts of the program. There is a lot of repeating so for keeping it easier to read and shorter I will so just parts of it..
for (int i = 0; i < buffer.size(); i++)
{
for (int j = 0; j < buffer[i].size(); j++)
{
if (j == 0) //first column
{
std::string s;
s = buffer[i][j];
if (s.size() == 0)
s = "NULL";
CSVFile.passwordName.push_back(s);
}
//...if(j==1) through (j==27)...//
if (j == 28) //Last column
{
std::string s;
s = buffer[i][j];
if (s.size() == 0)
s = "NULL";
CSVFile.extraPass3F.push_back(s);
}
}
}
valid = true;
return valid;
So as a workaround for the time being, I just place the word "NULL" in the last column and the code works as intended. Could the issue be that I am not handling "\n" when reading the line at "if(!std::getline(ss, s, ','))"?
Any help would be appreciated. Thanks in advance