basic_istream::seekg() in C++ with Examples
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/
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.