Re: Suggestions to reading txt files?
[please wrap your lines better]
On Thu, 2010-03-04, none wrote:
I have a .txt file containing strings ordered as a row*column matrix, eg.:
a basd asdasd asdasd ada asdasd asdda
b basd asdasd asdasd ada asdasd asdda
c basd asdasd asdasd ada asdasd asdda
c basd asdasd asdasd ada asdasd asdda
The number of columns for each row is constant. I am trying to write
a function that given a txt
file as the one above returns the i,j element like:
std::string file = "c:\test.txt";
int rows = numberOfRows(file);
int columns = numberOfColumns(file);
for (int i=0; i<rows; i++) {
for (int j=0; j<columns; j++) {
std::string elem = readCell(i,j,file);
}
}
Any hints on a smart version of readCell are welcome since my current
version is pretty ugly...
I assume the code above is *not* your current version; it would have
horrible performance since you have to read and parse the file
rows*columns+2 times.
maybe there are some build in functionality for this kind of txt
file parsing that I have missed ?
I'd not bother with istream >> str. If the file is small enough, I'd
read it line by line into a vector<string> and have a simple parser
string column(const string& row, int col);
Or a vector<vector<string> >, if that seems more efficient given how
you'll use it.
The code is really trivial to write, using just pointer arithmetics
and std::isspace().
Although I'd first consider if I *really* need random access to the
cells. It prevents pipelining (as in the Unix shell). If you can
manage with an interface which spits out row by row, you can support
interactive input, gzipped input, input from sockets, infinite input ...
/Jorgen
--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .