user
user

Reputation: 301

How to skip a string when reading a file line by line

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

Answers (1)

Jerry Coffin
Jerry Coffin

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.

  1. Don't use 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) ...
  2. The way you're reading right now really tries to read a "word" at a time, not a whole line. If you want to read a whole line, you probably want to use std::getline.

Upvotes: 6

Related Questions