In C++, peek() lets you look at the next character of an input stream without removing it. The character stays in the stream, so the next get() or >> still reads it.
This is useful for look-ahead: you decide what to do based on the next character before you read it. Include <iostream> to use it.
This is a member function of std::istream. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Call peek on an input stream. It takes no arguments.
C++
int next = in.peek();
if (std::isdigit(in.peek())) {
// a digit comes next
}
Call
What it does
in.peek()
Returns the next character as an int and leaves it in the stream.
in.peek() == '\n'
Checks whether the next character is a new line.
in.peek() == std::char_traits<char>::eof()
Checks whether there is nothing more to read.
Compare the result with a char like 'a' directly. Store it in an int, not a char, if you also want to detect the end.
Library declarations
C++
int_type peek();
Parameters
Parameter
Description
None
peek() takes no parameters.
Return Value
Return Value
Description
int_type
The next character, or EOF (usually -1) when the input has ended.
C++ Examples
Example 1 — peek() Does Not Remove the Character
Peek twice, then get once, and see the difference.