std::basic_istream::ignore in C++ with Examples
The std::basic_istream::ignore is used to extracts characters from the input string and discards them including delimiting character, i.e., if the end of the file is reached this function stops extracting characters. The delimiting character is the new line character i.e ‘\n’. This function will also stop extracting characters if the end-of-file is reached if the input is taken using a file. This function accesses the input sequence by first constructing a sentry object. It extracts characters from its associated stream buffer object and destroys the sentry object before returning.
Header File:
#include <iostream>
Syntax:
istream& ignore(size N,
int delim = EOF);
Parameters: It accepts the following parameters:
- N: It represent maximum number of characters to extract.
- delim: It is used for where stop the extraction.
Return Values: It returns the basic_istream object.
Below are the programs to demonstrate basic_istream::ignore():
Program 1:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
istringstream input(
"12\n"
"It is a string\n"
"14\n" );
for (;;) {
int n;
input >> n;
if (input.eof() || input.bad()) {
break ;
}
else if (input.fail()) {
input.clear();
input.ignore(
numeric_limits<streamsize>::max(),
'\n' );
}
else {
cout << n << '\n' ;
}
}
return 0;
}
|
Program 2:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
char first, last;
cout << "Enter a String: " ;
first = cin.get();
cin.ignore(256, ' ' );
last = std::cin.get();
cout << "Your initials are "
<< first << ' '
<< last << '\n' ;
return 0;
}
|
Output:
Reference: http://www.cplusplus.com/reference/istream/basic_istream/ignore/
Last Updated :
10 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...