read file separated comma c++ code example

Example 1: how to read a comma delimited file into an array c++

#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>

int main()
{
    std::ifstream inFile("registration.txt");
    if (inFile.is_open())
    {
        std::string line;
        while( std::getline(inFile,line) )
        {
            std::stringstream ss(line);

            std::string ID, fname, lname;
            std::getline(ss,ID,',');    std::cout<<"\""<<ID<<"\"";
            std::getline(ss,fname,','); std::cout<<", \""<<fname<<"\"";
            std::getline(ss,lname,','); std::cout<<", \""<<lname<<"\"";

            std::vector<std::string> enrolled;
            std::string course;
            while( std::getline(ss,course,',') )
            {
                 enrolled.push_back(course); std::cout<<", \""<<course<<"\"";
            }
            std::cout<<"\n";
        }
    }
    return 0;
}

Example 2: read comma separated text file in c++

#include <iostream>
#include <fstream>
#include <string>

ifstream file("filename.txt");
string data = "";
while(getline(file, data,','))
{
  cout << data << endl;
}
file.close();

Tags:

Cpp Example