In: Computer Science
Write a C++ function that reads a .csv file(file contains rows of string(name) and number) into a vector and loop through that vector and find the max number.
#include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <vector> using namespace std; vector<string> readFile(string file) { ifstream f(file.c_str()); vector<string> lines; string line; while(f >> line) { lines.push_back(line); } f.close(); return lines; } int main() { vector<string> lines = readFile("input.csv"); // Find max number. int max = 0; for(int i=0; i<lines.size(); i++) { string line = lines[i]; stringstream ss(line); int x; string n; // read till comma getline(ss, n, ','); if(ss.peek() == ',') { ss.ignore(); } ss >> x; if(x > max) { max = x; } } cout << "the max number from file is: " << max << endl; }
===============
input.csv:
First,23
Second,43
Third,56
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.