It depends on how it's stored.
Generally, if you're the one defining the rules, I'd go with fstream, and use >> and << operators for both saving and loading.
This way, it's easy to get data.
Look at my example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
//Loading file - LevelLoader.cpp
/**
* A function loading level from a file
* @param con A vector for storing Blocks from file
* @param filepath The path of file containing data
* @return Function returns false if couldn't open file, otherwise returns true
*/
bool LevelLoader::LoadLevel(std::vector<Block>& con, std::string filepath)
{
std::ifstream file(filepath); // Create a file stream, open file
if(!file.good()) // If we encounter error, return false
{
return false;
}
if(file.is_open() )
{
while(file.good() )
{
//Each file line looks like this(example):
// 25 64 3
int xpos;
int ypos;
int colorIndex;
file >> xpos;
file >> ypos;
file >> colorIndex;
con.push_back(Block(xpos, ypos, colorIndex));
}
con.pop_back();//Including one empty line.
}
else
{
return false;
}
return true;
}
| |
I had to make small hack with pop_back(), but it's because that how I stored it.
As you see, I can extract needed data from file.
And function that saves it is just as similar
1 2 3 4 5 6 7 8
|
void CreatorState::Save()
{
for(auto& it : m_BlockContainer)
{
levelFile << it.GetX() <<' '<< it.GetY()<<' '<<it.GetHp()<<std::endl;
}
levelFile.flush();
}
| |
Which you could read like "For each element in m_BlockContainer, take its X, Y and HP, and store them in the file.
I'm pretty sure that if you experiment you'll do it without problem.
Cheers!
PS. If you don't want to use >> operator, then your code has a following flaw - you get line from file, but you never parse input string - you need to go through string and separate each element, take it out from string and store in proper array.