I'm trying to learn on how to read data from .csv file. The code shows that the data from csv file is read line by line. After the data is stored on variable
string arrival;
, the substring from arrival
is taken but I'm stuck on on how to take the substring of the first column from each row. Is there an alternative way to read the data from csv? This is the output.
#include<iostream>
#include<fstream>
#include<string>
#include<string.h>
#include<exception>
#include<sstream>
using namespace std;
int main()
{
string arrival,burst[1000];
char string[] ="Job";
char *tokenptr;
int x=0;
tokenptr = strtok(string," ");
ifstream jobfile("job.csv");
if(jobfile.is_open())
{
cout << "Successfully open file"<<endl;
while(jobfile!=NULL)
{
getline(jobfile,arrival,',');
cout << arrival << endl;
try
{
if(arrival.length() < 30)
{
std::string jobstr = arrival.substr (28,1); //To take substring from arrival
stringstream job(jobstr);
int jobArr; // To convert string into integer
job >> jobArr;
cout<<"Job Arrival = " << jobArr <<endl;
}
if(arrival.length() == 30)
{
std::string jobstr = arrival.substr (29,2);
stringstream job(jobstr);
int jobArr;
job >> jobArr;
cout<<"Job Arrival = " << jobArr <<endl;
}
if(arrival.length() > 30)
{
std::string jobstr = arrival.substr (30,2);
stringstream job(jobstr);
int jobArr = 0;
job >> jobArr;
cout<<"Job Arrival = " << jobArr <<endl;
}
}
// To check exception
catch (std::exception const &exc)
{
std::cerr << "Exception caught " << exc.what() << "\n";
}
catch (...)
{
std::cerr << "Unknown exception caught\n";
}
for(int i=0;i < 4;i++)
{
getline(jobfile,burst[i],',');
cout<<burst[i]<<endl;
}
tokenptr=strtok(NULL," ");
if(tokenptr==0)
{
x+=1;
}
}
cout<<"Number of Job ="<< x <<endl;
}
jobfile.close();
}