Reading two columns in CSV file in c++ -
i have csv file in form of 2 columns: name, age
to read , store info, did this
struct person { string name; int age; } person record[10]; ifstream read("....file.csv");
however, when did
read >> record[0].name; read.get(); read >> record[0].age;
read>>name gave me whole line instead of name. how possibly avoid problem can read integer age?
thank you!
you can first read whole line std:getline
, parse via std::istringstream
(must #include <sstream>
), like
std::string line; while (std::getline(read, line)) // read whole line line { std::istringstream iss(line); // string stream std::getline(iss, record[0].name, ','); // read first part comma, ignore comma iss >> record[0].age; // read second part }
below working general example tokenizes csv file live on ideone
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> int main() { // in case you'll have file // std::ifstream ifile("input.txt"); std::stringstream ifile("user1, 21, 70\nuser2, 25,68"); std::string line; // read full line here while (std::getline(ifile, line)) // read current line { std::istringstream iss{line}; // construct string stream line // read tokens current line separated comma std::vector<std::string> tokens; // here store tokens std::string token; // current token while (std::getline(iss, token, ',')) { tokens.push_back(token); // add token vector } // can process tokens // first display them std::cout << "tokenized line: "; (const auto& elem : tokens) std::cout << "[" << elem << "]"; std::cout << std::endl; // map tokens our variables, applies scenario std::string name = tokens[0]; // first string, no need further processing int age = std::stoi(tokens[1]); // second int, convert int height = std::stoi(tokens[2]); // same third std::cout << "processed tokens: " << std::endl; std::cout << "\t name: " << name << std::endl; std::cout << "\t age: " << age << std::endl; std::cout << "\t height: " << height << std::endl; } }
Comments
Post a Comment