Peek () A few places ahead?

Suppose I have an external while loop to read each character and output it to the console. I also want to mark the word if it is found, and with the peek method I can find the first instance of the word. Is there a way to look a few places ahead. For example, if I search for the word "payday". I know that I can type this into a string and search for a string, but I want to read files in binary mode, and I don't want to remove any values ​​from the outer loop. If I have an inner loop with a read method, these values ​​are then not displayed through the outer loop.

thanks

int main()

ifstream strm;
char *chr = new char;

strm.open("mytext.txt",ios::out | ios::binary);

while (strm.read(chr,1)
{
    if (strm.peek() == 'p';
  {
    cout << "found a word beginning with 'p'" << endl;
  //what if I want to read multiple characters ahead.  Peek will read only one.
  }

}
+4
source share
2 answers

seekg , istream.

, tellg, , .

, , (.. strm.seekg(offset, strm.cur)), - , , newline, tellg seekg . , , "p", n-, -n, , .

+5

, - : lexer.

, Lexer :

class Lexer {
public:
    Lexer(std::istream& s): source(s) { this->read(); }

    explicit operator bool() const {
        return not queue.empty();
    }

    Lexer& operator>>(std::string& s) {
        assert(*this and "Test for readiness before calling this method");

        s = queue.front();
        queue.pop_front();

        if (queue.empty()) { this->read(); }
        return *this;
    }

    std::string const* peek(size_t const i) {
        while (source and queue.size() < i) { this->read(); }
        return queue.size() >= i ? &queue[i] : nullptr;
    }

private:
    void read() {
        queue.emplace_back();
        if (not (source >> queue.back())) { queue.pop_back(); }
    }

    std::istream& source;
    std::deque<std::string> queue;
}; // class Lexer

. , lexer - , , ..... , !

+4

All Articles