read a string from file split by comma into array c++ code example

Example 1: c++ split string by comma into array

#include <vector>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int main()
{
    string s="i,love,my,country,very,much";   //declare a string
    string answer[6];  // string array to store the result
    stringstream string_stream(s);  // creating string stream object
	int i=0;            // declaring i and assign  to 0
   
	while(string_stream.good())   // loop will continue if string stream is error free
	{
		string a;       
		getline( string_stream, a, ',' );   //calling getline fuction
		answer[i]=a;
		i++;
	}
   
	for(i=0;i<6;i++)
	{
		cout<<answer[i]<<endl;   // printing a result
	}
    return 0;
}

Example 2: 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;
}

Tags:

Cpp Example