Open In App

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

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

The basic_stream::seekg() method is used to set position of the next character to be extracted from the input stream. This function is present in the iostream header file. Below is the syntax for the same:

Header File:

#include<iostream>

Syntax:

basic_istream& seekg (pos_type pos);

Parameter:

  • pos: It represents the new position in the buffer .

Return Value: This function returns the basic_istream object.

Below is the program to illustrate std::basic_istream::seekg()

Program 1:




// C++ code for basic_istream::seekg()
  
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    string str = "Geeks for Geeks";
    istringstream gfg(str);
    string a, b;
  
    gfg >> a;
    gfg.seekg(0); // rewind
    gfg >> b;
  
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
}


Output:

a = Geeks
b = Geeks

Program 2:




// C++ code for basic_istream::seekg()
  
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    string str = "Geeks for Geeks";
    istringstream gfg(str);
    string a, b;
  
    gfg >> a;
    gfg.seekg(6); // rewind
    gfg >> b;
  
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
}


Output:

a = Geeks
b = for

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads