Reputation: 301
I have managed to skip the name section when reading values from a file with name and value pairs. But is there another way to skip the name section without declaring a dummy string to store the skipped data?
Example text file: https://i.sstatic.net/94l1w.png
void loadConfigFile()
{
ifstream file(folder + "config.txt");
while (!file.eof())
{
file >> skip;
file >> screenMode;
if (screenMode == "on")
notFullScreen = 0;
else if (screenMode == "off")
notFullScreen = 1;
file >> skip;
file >> playerXPosMS;
file >> skip;
file >> playerYPosMS;
file >> skip;
file >> playerGForce;
}
file.close();
}
Upvotes: 4
Views: 12884
Reputation: 490048
You can use std::cin.ignore
to ignore input up to some specified delimiter (e.g., a new-line, to skip an entire line).
static const int max_line = 65536;
std::cin.ignore(max_line, '\n');
While many people recommend specifying a maximum of something like std::numeric_limits<std::streamsize>::max()
, I do not. If the user accidentally points the program at the wrong file, they shouldn't wait while it consumes an inordinate amount of data before being told something's wrong.
Two other points.
while (!file.eof())
. It mostly leads to problems. For a case like this, you really want to define a struct
or class
to hold your related values, define an operator>>
for that class, then use while (file>>player_object) ...
std::getline
.Upvotes: 6