I am unable to read the contents of a 30 row .csv file into the following struct:
class Entry {
public:
std::string GID;
std::string DName;
std::string Phone;
std::string POC;
std::string Item;
std::string Category;
double amount;
};
I want to be able to create a function that can read the csv file dubbed "Donations.csv" and remove the commas because I would like to create a vector possibly like this: std::vector<Entry> entries;
so that I can sort the multiple items based on whatever element in the vector. So for example say I would want to sort by DName, the code would look something like this:
// sort by DName
std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) {
return a.DName.compare(b.DName) < 0;
});
I was told not to use multiple vectors as this not safe and efficient however if it may help someone, this is how to read a csv file into multiple vectors:
FAIR WARNING, USING THE EOF CONTROLLER IS WRONG, REFER HERE
Albeit, this code will work just ok, I have personally tested it - numerous times on .csv files.
int main()
{
ifstream inFile; // Input file handler
ofstream outFile; // Output file handler
vector<string> GID; // Vector holding Gift ID
vector<string> DName; // Vector holding Donor Name
vector<string> Phone; // Vector holding Phone Number
vector<string> POC; // Vector holding point of contact
vector<string> Item; // Vector holding item donated
vector<string> Category; // Vector holding type of item donated
vector<double> amount; // Vector holding amount of donated items
int Input; // User selection choice from menu
// opening data file
inFile.open("Donations.csv");
if (!inFile) // If statement to check for file erroe
{
cout << "Input file did not open. Program will exit." << endl; // Does not compute!
exit(0);
}
// reading contents
string str; // temp string to hold parse comma
double temp; // temp double to hold null spaces for atoi function/strtod
getline(inFile, str, ','); // read first GID string outside of loop so that we
// won't accidentally reach the end of the file in the MIDDLE of the loop
while (!inFile.eof()) // end of file not reached
{
GID.push_back(str);
getline(inFile, str, ','); // get the contents of the line until a comma is encountered and push it into the necessary vector
DName.push_back(str);
getline(inFile, str, ',');
Phone.push_back(str);
getline(inFile, str, ',');
POC.push_back(str);
getline(inFile, str, ',');
Item.push_back(str);
getline(inFile, str, ',');
Category.push_back(str);
getline(inFile, str, '\n'); // get until the end of the line but split for parsing
// convert string to double using strtod and c_str
temp = strtod(str.c_str(), NULL);
// now push double onto vector
amount.push_back(temp);
getline(inFile, str, ','); // read in GID here instead of the top. If we are at the end
// of the file, it won't work and end-of-file flag will be set which is what we want.
}
inFile.close();
}