I also tried the same process just using getline() instead, but I have the same problem, it just reads and re-reads the file infinitely.
You should have shown us the std::getline
code which doesn't work. Using std::getline
is certainly the preferred solution here. Did you, by any chance, use the member function instead of the free-standing function which works with std::string
? sprintf
and arrays are the wrong tools for this task.
Here's what you should do:
- Read whole lines with the free-standing
std::getline
function. - Use
std::getline
's returnedstd::ifstream
itself in the loop condition (it will work due to operator overloading). - Tokenize each line after reading it. Did you consider what would happen in your program if a player has two first names? Shouldn't this at least result in a meaningful error message?
- Use
std::string
'sc_str
member function to safely pass strings toDrawScreenString
.
Example:
std::string line;
while (std::getline(scores, line) && (i < 8))
{
std::vector<std::string> const tokens = tokenize(line);
// ...
DrawScreenString(GAX1 + 20, GAY1 + 120 + line, tokens[0].c_str(), 0x505050, pBody);
// and so on
}
The remaining interesting question is how to write the tokenize
function:
std::vector<std::string> tokenize(std::string const &line)
{
// ?
}
Perhaps Boost Tokenizer can help you. But you could also just use std::string
's member functions like find
and substr
.
Just to give you an idea:
std::vector<std::string> tokenize(std::string const &line)
{
std::vector<std::string> result;
std::string::size_type const pos_first_space = line.find(" ");
if (pos_first_space == std::string::npos)
{
// error, no space found
}
std::string const first_token = line.substr(0, pos_first_space);
result.push_back(first_token);
// ...
return result;
}
The point is: separate reading a line from tokenizing a line.