Open In App

basic_istream::peek() in C++ with Examples

Last Updated : 28 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The std::basic_istream::peek() used to reads the next character from the input stream without extracting it. This function does not accept any parameter, simply returns the next character in the input string. Below is the syntax for the same:

Header File:

#include<iostream>

Syntax:

int peek();

Return Value: The std::basic_istream::peek() return a next character in the input string.

Below are the programs to understand the implementation of std::basic_istream::peek() in a better way:

Program 1:




// C++ code for std::basic_istream::peek()
#include <bits/stdc++.h>
using namespace std;
  
// main method
int main()
{
    istringstream gfg("GeeksforGeeks");
  
    char c1 = gfg.peek();
    char c2 = gfg.get();
    char c3 = gfg.get();
  
    cout << "The first character is: "
         << c1 << endl
         << " and the next is: "
         << c3 << endl;
}


Output:

The first character is: G 
and the next is: e

Program 2:




// C++ code for std::basic_istream::peek()
#include <bits/stdc++.h>
using namespace std;
  
// main method
int main()
{
    istringstream gfg("Computer");
  
    char c1 = gfg.peek();
    char c2 = gfg.get();
    char c3 = gfg.get();
  
    cout << "The first character is: "
         << c1 << endl
         << " and the next is: "
         << c3 << endl;
}


Output:

The first character is: C 
and the next is: o

Program 3:




// C++ code for std::basic_istream::peek()
#include <bits/stdc++.h>
using namespace std;
  
// main method
int main()
{
    istringstream gfg("Laptop");
  
    char c1 = gfg.peek();
    char c2 = gfg.get();
    char c3 = gfg.get();
    char c4 = gfg.get();
  
    cout << "The first character is: "
         << c1 << endl
         << " and the next is: "
         << c3 << endl
         << " after that next is: "
         << c4 << endl;
}


Output:

The first character is: L 
and the next is: a 
after that next is: p

Reference: http://www.cplusplus.com/reference/istream/basic_istream/peek/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads