Skip to content
Related Articles

Related Articles

basic_istream::seekg() in C++ with Examples
  • Last Updated : 28 May, 2020

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

a = Geeks
b = Geeks

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

a = Geeks
b = for

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

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :