ifstream stuck on `\n` when trying to read the previous character

84 Views Asked by At

I'm writing a brainfuck interpreter in C++. One of its language features is that in a loop if the current byte != 0 then go back to the beginning of the loop until it's == 0. My approach is reading a file character by character instead of loading the whole file into memory. I use ifstream::seekg to go back to the previous character:

[[nodiscard]] inline BFInstruction prev_inst()
{
    if (m_file.eof())
        m_file.clear(); // clear eof bit

    m_file.seekg(-2, std::ios::cur); // -1 is the current char so -2 for the previous

    return to_inst(static_cast<char>(m_file.get()));
}

It all works until the previous character is a \n like in this example:

++++++[>++++++++<-
]>>++[>+++++<-]>[<<.+>>-]

m_file.get() always returns \n when the current position is the beginning of a line instead of in this case -. How do I fix that?

UPDATE

Here's a reproducible example:

main.cpp

#include <iostream>
#include <fstream>

char next(std::ifstream &f)
{
    char next;
    do
    {
        next = f.get();
    } while (next == '\n');

    return next;
}

char prev(std::ifstream &f)
{
    f.seekg(-2, f.cur);

    return f.get();
}

int main()
{
    std::ifstream f("../example.txt");

    std::cout << next(f) << '\n'; // `a`
    std::cout << next(f) << '\n'; // `b` (because \n is ignored)
    std::cout << prev(f) << '\n'; // '\n'
    std::cout << prev(f) << '\n'; // `\n` again no matter how many times
                                  // we call `prev()` when we would expect
                                  // `a` to be the previous char

    return 0;
}

example.txt

a
bc
0

There are 0 best solutions below