Search code examples
c++ifstream

How can I stream different lines of input from one text file?


I'm trying to create a simulation in which I have objects moving within a rectangular grid. Information is given in the form of a text file. Sample input is as follows:

5 5
0 1 N
PFPFFSF
2 3 S
FSFFSFFSPF

First line is the dimension of the grid (in this case 5 x 5 assuming the bottom left coordinate is 0,0)

The rest of the input is just info in regards to the object and how it moves. Each object has 2 lines of input. First line is it's starting coordinates and orientation while the second line describes its movements.

When using an input stream, how can I grab the input so that it groups accordingly?

I know for the first line, I can just use

simulationSettings >> x >> y;

to grab the size of the grid.

However, is there a way of grabbing the rest of the input and grouping the info by 2 lines (for each object)?

So, for example, stream the input so that my object1 will have 0 1 N and PFPFFSF while object 2 has 2 3 S and FSFFSFFPF and so on should there be more objects.


Solution

  • If you can simply ignore how the file is actually structured in line, you structure is just:

    • 2 integer values for the grid size
    • n times (per object):
      • 2 integers for the initial position
      • one string for the initial direction
      • one string for the movements

    You could just use:

    simulationSettings >> x >> y;
    if (! simulationSettings.good()) {
        // process error condition and exit
    }
    for(;;) {
        int xinit, yinit;
        std::string direction, movements;
        simulationSettings >> xinit;
        if (simulationSettings.eof()) break; // normal end of file
        simulationSetting >> yinit >> direction >> movements;
        if (! simulationSettings.good()) {
            // process error condition and at least break from the loop
        }
        // process the object
    }