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";
string answer[6];
stringstream string_stream(s);
int i=0;
while(string_stream.good())
{
string a;
getline( string_stream, a, ',' );
answer[i]=a;
i++;
}
for(i=0;i<6;i++)
{
cout<<answer[i]<<endl;
}
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;
}