The peek()
method in input streams allows you to look at the next character in the stream without extracting it. This can be useful in several scenarios.
One common use of peek()
is to check if you've reached the end of the file (EOF). This is especially useful when you need to verify if more input is available before attempting to read:
#include <iostream>
#include <sstream>
int main() {
std::istringstream input{"Hello\nWorld\n"};
std::string extract;
while (std::getline(input, extract)) {
std::cout << "Extracted: " << extract << '\n';
if (input.peek() == EOF) {
std::cout << "Reached EOF\n";
}
}
}
Extracted: Hello
Extracted: World
Reached EOF
In this example, peek()
helps to check if the end of the stream is reached after reading lines.
peek()
is also useful when you need to decide on an action based on the next character in the stream. For example, you might want to process input differently if the next character is a specific delimiter or a certain value:
#include <iostream>
#include <sstream>
int main() {
std::istringstream input{"1234A5678"};
char nextChar;
while (input.get(nextChar)) {
if (std::isdigit(input.peek())) {
std::cout << "Next is a digit\n";
} else {
std::cout << "Next is not a digit\n";
}
}
}
Next is a digit
Next is a digit
Next is a digit
Next is not a digit
Next is a digit
Next is a digit
Next is a digit
Next is a digit
Next is not a digit
Here, peek()
checks the next character without consuming it, allowing the program to branch logic based on the lookahead character.
Using peek()
, you can repeatedly check the same character without moving the input position. This is useful in parsers or situations where multiple operations might be needed on the same upcoming character:
#include <iostream>
#include <sstream>
int main() {
std::istringstream input{"Hello World"};
char ch;
while (input.get(ch)) {
std::cout << "Char: " << ch << '\n';
std::cout << "Peek: " << static_cast<char>(input.peek()) << '\n';
}
}
Char: H
Peek: e
Char: e
Peek: y
Char: y
Peek:
This program shows how peek()
can be used to preview the next character without extracting it.
Using peek()
effectively can help manage input streams more precisely, ensuring your program handles input correctly without prematurely consuming characters.
Answers to questions are automatically generated and may not have been reviewed.
A detailed introduction to C++ Input Streams using std::cin
and istringstream
. Starting from the basics and progressing up to advanced use cases including creating collections of custom objects from our streams.