Re: Suggestions to reading txt files?
"none" <""mort\"@(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'll bet!
... maybe there are some build in functionality for this kind
of txt file parsing that I have missed ?
Yes. Don't parse text files! That's broken.
Instead, read a whole line of text into a std::string,
using std::string::getline(). That allows you to use the rich set
of functions that come with std::string to operate on the string.
Also, it allows you to put the string into a std::stringstream,
so you can easily parse it into "words" with >>.
Something like:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
void ParseFileLinesToWords (const std::string& file_name)
{
std::string Line;
std::string Word;
// ... code here to add any other variables you might need,
// such as an array or 2-d vector to hold words....
std::ifstream SourceFile (file_name.c_str());
if (not SourceFile.is_open() or StreamIsBad(SourceFile)) {return;}
while (1)
{
getline(SourceFile, Line);
if (StreamIsBad(SourceFile)) {return;}
if (SourceFile.eof()) {break;}
std::stringstream StreamLine (Line);
while ( StreamLine >> Word )
{
// ... code to add current Word to a cell in an array,
// or perhaps a 2-d vector of strings,
// std::vector<std::vector<std::string> > ....
}
}
// ... code here to do something with your array of words....
return;
}
Incomplete and untested, but should get you on right track!
Look up "stringstream" in any C++ book (or google it) for
more info.
--
Cheers,
Robbie Hatley
lonewolf at well dot com
www dot well dot com slant tilde lonewolf slant