parsing a .csv

Can anyone provide any tips for parsing a .csv?

I’m coming from Processing where I usually use loadStrings like so:

  
  
String[] file = loadStrings("myFile.csv");  
  
for (int i=0; i<file.length; i++)  
{  
    String[] data = file[i].split(",");  
    float someFloat = Float.parseFloat(data[0]);  
    int someInt = Integer.parseInt(data[1]);  
    // Etc...  
}  
  

But based on what I know about C++ strings so far, I’m guessing its not gonna be so simple. Can anyone point me in the right direction? Thanks.

-Aaron

I thought of included some kind of file reading utility but I can find it at the moment. This method for reading in a file might not work if you’re not on osx/linux (I don’t really know a ton about win, but I’m sure you can figure out how to get the file). Really all you need to do is make a vector and then look through each line of the file and use the substr method to break the string whereever you find a comma. It’s a bit messier than the Prcs way, and there’s probably some magic parser buried in the Poco libs, but this works well enough:

  
void readAndParseCSV(vector<string>* array) {  
	string line;  
	int pos;  
	ifstream in("test.csv");  
	if(!in.is_open())  
	{  
		printf(" can't open the file ");  
		return;  
	}  
	while( getline(in,line) )  
	{  
		while( (pos = line.find(',')) >= 0)  
		{  
			string field = line.substr(0,pos);  
			line = line.substr(pos+1);  
			array->push_back(field);  
		}  
	}  
	return;  
}  

Just note that in order to affect the vector you’re passing in you have to pass a pointer to it rather than a reference (hence the *). You’d call it like this:

  
	vector<string> array;  
	readAndParseCSV(&array);  

I’m sure someone knows a better way of doing that, but it seems to work well enough. The next problem is the cast.

atoi gives you integers from chars, which means you can call it like this:

atoi(array[i].c_str()); // note array[i].c_str() , not just array[i]

atof gives you floats from chars. Those are kinda frowned on by serious C++ people but they prefer templating just for a simple cast, and I think that’s a bit overkill. You can also use istringstream like this:

  
istringstream iss(array[i]);  
int val;  
iss >> val;  
printf("%i", val);  

which is better and there’s info on it here:

http://www.parashift.com/c+±faq-lite/m-…-l#faq-39.2

Hope that helps.