For this assignment we are going to do some file IO. Attached is a database file
ID: 3686913 • Letter: F
Question
For this assignment we are going to do some file IO. Attached is a database file with comma separated values. The values are in the format (index, first name, last name, address, city, state, zip). There are duplicates in this database file. Read in the database, remove the duplicates, and write a new comma separated database file without the duplicates. The index field in the new file must be sequential and start at one. Do not design your program to the provided data file. Your submitted program will be run against other files of the same format. Program tasks: Prompt the user for the database file name. This file name is the path and the file name. For example "/home/student/lab8/Resource/database.csv". Do not assume the file is in a particular directory. Open the database Read in the records using a custom class to hold a record Remove the duplicates Write the scrubbed database as a new CSV file starting with 'new_' and the input database file name. The index field in the new file must be sequential and start at one. Write the new file to the same directory that the database file was read from. For example "/home/student/lab8/Resource/new_database.csv" Some suggestions: Create a class to hold a single data record. Override the == operator to ease comparison and override the << operator to output the comma separated values. Use the class constructor to receive a line from the database then parse the values or override the >> input operator. Modify the string stream getline() delimiter to a comma. See http://en.cppreference.com/w/cpp/string/basic_string/getline (Links to an external site.) Use a vector to contain your data records. Do not read the zip code as an integer While the provided database file contains valid data be aware of potential errors from bad data records. Do not go overboard on error checking. Do not write your program just for the attached data file
Explanation / Answer
#include #include #include #include #include #include class CSVRow { public: std::string const& operator[](std::size_t index) const { return m_data[index]; } std::size_t size() const { return m_data.size(); } void readNextRow(std::istream& str) { std::string line; std::getline(str,line); std::stringstream lineStream(line); std::string cell; m_data.clear(); while(std::getline(lineStream,cell,',')) { m_data.push_back(cell); } } private: std::vector m_data; }; std::istream& operator>>(std::istream& str,CSVRow& data) { data.readNextRow(str); return str; } int main() { std::ifstream file("database.csv"); CSVRow row; while(file >> row) { std::coutRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.