struct geneInfo
{
int ID;
float length;
float readCNT;
};
int main()
{
// Better to use the constructor to open the file.
ifstream myfile("/Users/T_HEN1203/Desktop/DarkAerobic.csv");
// Don't forget to check that the file open operation succeeds!
...
std::vector<geneInfo> genes;
// Read the file;
int id;
float length, readCNT;
char delimiter;
// Read the file.
while(myfile >> id >> delimiter >> length >> delimiter >> readCNT)
{
genes.push_back({id, length, readCNT});
}
}
Since it appears that the first line of your csv file is the heading text, you will need to skip that before starting to read the actual data. For example, you could put
myfile.ignore(1000, '\n');
to ignore up to 1000 characters, or until the newline is found.
struct geneinfo {
int ID;
float length;
float readCNT;
};
//function protoypes
void Print_geneinfo(geneinfo g);
int main(){
ifstream myfile("/Users/T_HEN1203/Desktop/DarkAerobic.csv"); //file opening constructor
//Operation to check if the file opened
if ( myfile.is_open() ){
vector<geneinfo> genes;
int id;
float length, readCNT;
char delimiter;
// Read the file.
myfile.ignore(1000, '\n');
while(myfile >> id >> delimiter >> length >> delimiter >> readCNT){
genes.push_back({id, length, readCNT});
}
cout << "Gene ID" << " DNA Length" << " Read counts \n";
for (int x(0); x < genes.size(); ++x){
Print_geneinfo( genes.at(x) );
}
}
else{
cerr<<"ERROR: The file isnt open.\n";
}
return 0;
}
// function definitions
//------------------------------------------------------------------------------
//function to print info
void Print_geneinfo(geneinfo g){
cout << g.ID << " "<< g.length <<" "<< g.readCNT << "\n";
}
EDIT: Everything seems to work and it displays correctly. It looks like im not using #include <sstream> anymore and i read somewhere that csv files are read as strings so i was curious as to what converts it to int and float?
i read somewhere that csv files are read as strings
Presumably that was just one possible approach which you read about. As you can see, the code suggested by jlb does not follow that approach. The choice is yours. A csv file is after all just a text file, you can handle it in whichever way seems best.
so i was curious as to what converts it to int and float?
It's just the same in principle as when you do cin >> id; or cin >> length;. That is, the input is in the form of text and the >> operator of the stream does the conversion for you.