Search code examples
c++arraysifstream

C++: How to read multiple lines from file until a certain character, store them in array and move on to the next part of the file


I'm doing a hangman project for school, and one of the requirements is it needs to read the pictures of the hanging man from a text file. I have set up a text file with the '-' char which means the end of one picture and start of the next one.

I have this for loop set up to read the file until the delimiting character and store it in an array, but when testing I am getting incomplete pictures, cut off in certain places.

This is the code:

string s;
ifstream scenarijos("scenariji.txt");

    for(int i = 0; i < 10; i++ ) {
        getline(scenarijos, s, '-');
        scenariji[i] = s;
    }

For the record, scenariji is an array with type of string

And here is an example of the text file: example


Solution

  • From your example input, it looks like '-' can be part of the input image (look at the "arms" of the hanged man). Unless you use some other, unique character to delimit the images, you won't be able to separate them.

    If you know the dimensions of the images, you could read them without searching for the delimiter by reading a certain amount of bytes from the input file. Alternatively, you could define some more complex rules for image termination, e.g. when the '-' character is the only character in the line. For example:

    ifstream scenarijos("scenariji.txt");
    string scenariji[10];
    for (int i = 0; i < 10; ++i) {
        string& scenarij = scenariji[i];
    
        while (scenarijos.good()) {
            string s;
            getline(scenarijos, s); // read line
    
            if (!scenarijos.good() || s == "-")
                break;
    
            scenarij += s;
            scenarij.push_back('\n'); // the trailing newline was removed by getline
        }
    }