The C++ std::istream::peek() function is used to examine the next character in the input stream without extracting it. It allows to preview the upcoming character while keeping it in the stream for future use. It returns the next character as an int or EOF (if the end of the stream is reached).
SyntaxUnlike, the get(), which removes the character from the stream, peek() maintains the streams state unchanged.
Following is the syntax for std::istream::peek() function.
int peek();Parameters
It does not accept any parameter.
Return ValueThis function returns the next character in the input sequence.
ExceptionsIf an exception is thrown, the object is in a valid state.
Data racesModifies the stream object.
ExampleIn the following example, we are going to consider the basic usage of the peek() function.
#include <iostream> #include<sstream> int main() { std::istringstream a("Welcome"); char x = a.peek(); std::cout << "Peeked Character : " << x << std::endl; return 0; }Output
Output of the above code is as follows −
Peeked Character : WExample
Consider the following example, where we are going to use the peek() function along with the ignore().
#include <iostream> #include<sstream> int main() { std::string a = "ABC"; std::istringstream x(a); x.ignore(); char y = x.peek(); std::cout << "Peeked Character : " << y << std::endl; return 0; }Output
Following is the output of the above code −
Peeked Character : BExample
Let's look at the following example, where we are going to use the peek() along with the isalpha() to check if it is an alphabetic character.
#include <iostream> #include <cctype> #include<sstream> int main() { std::string x = "1A2B"; std::istringstream y(x); char a = y.peek(); if (std::isalpha(a)) { std::cout << "Next character is alphabetic: " << a << std::endl; } else { std::cout << "Next character is not alphabetic: " << a << std::endl; } return 0; }Output
If we run the above code it will generate the following output −
Next character is not alphabetic: 1
istream.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4