I have a text file with some data in it, and I'm trying to read it into my objects.
It's a fairly simple format consisting of a filename, a pair of dimension values, then a list of value-pairs:
StringFileName
IntWidth IntHeight
IntA:IntB IntA:IntB IntA:IntB
IntA:IntB IntA:IntB IntA:IntB
IntA:IntB IntA:IntB IntA:IntB
For example:
MyFile.txt
3 3
1:2 3:4 4:5
9:2 1:5 2:1
1:5 8:3 4:2
There may be more unrelated text here
Here's what I have so far:
void OnLoad(char* InputFilename) {
string Filename;
int Width;
int Height;
// open the file
ifstream inputFile(InputFilename);
// get the filename
getline(inputFile, Filename);
cout << "Filename is " << Filename << endl;
// get the width and height
string dataLine;
getline(inputFile, dataLine);
stringstream ss(dataLine);
ss >> Width;
ss >> Height;
cout << "Dimensions are " << Width << "x" << Height << endl;
// get the lines of tile-data
for (int Y = 0; Y < Height; Y++) {
/*
* Here is where I'm getting stuck.
* I have a string of "i:i i:i i:i" values, and I get a series of strings
* of "i:i" values, but can't work out the neatest way of splitting it out.
*/
getline(inputFile, dataLine);
stringstream row(dataLine);
for (int X = 0; X < Width; X++) {
int IntA;
int IntB;
// ?
DoStuffWith(IntA, IntB);
}
}
}
Something like this should work
std::ifstream file("filename");
std::string file_name;
int height, width;
file >> file_name >> height >> width;
// i don't know what your format is but it isn't very importance
std::deque<std::pair<int, int> > pairs;
std::string line;
int i, j;
char a;
while(std::cin >> i >> a >> j) //here i j are values in your pair.
{
if(a!=':') break;
pairs.push_back(std::make_pair(i, j));
}
Boost's split function can divide on arbitrarily many predicates. So you could do something like:
vector<string> results;
boost::split( results, data_string, boost::is_any_of(" :") ); <- splits on spaces and ":"
Then you have all the data in a handy container!
Maybe not the best solution in your case but it's good to keep in mind.
Now you can use the "*i" and assign the int values that you get in a more clean way.
std::string line;
do{
getline(inputFile,line);
sregex_token_iterator end;
for(sregex_token_iterator i(line.begin(), line.end(), pattern,-1); i!=end;++i)
{
cout<< *i << " " ;
}
}while(!inputFile.eof());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.