C++ istream::ignore() function



The C++ std::istream::ignore() function is used to skip or ignore characters in an input stream. It is useful for clearing out unwanted characters or handling input that contains extra characters after reading the expected data.

If the number of characters or the delimiter is specified, it will skip that many characters or until the delimiter is encountered.

Syntax

Following is the syntax for std::istream::ignore() function.

istream& ignore (streamsize n = 1, int delim = EOF);

Parameters

  • n − It indicates the maximum number of characters to extract.
  • delim − It indicates the delimiting character.

Return Value

This function returns the basic_istream object (*this).

Exceptions

If an exception is thrown, the object is in a valid state.

Data races

Modifies the stream object.

Example

Let's look at the following example, where we are going to skip the fixed number of characters.

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream x("ABTutorialsPoint.");
    x.ignore(2);
    std::string y;
    std::getline(x, y);
    std::cout << "Result :  " << y << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Result :  TutorialsPoint.

Example

Consider the following example, where we are going to use the ignore() function to skip the space between the numbers.

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream x("11 12 23");
    int a, b, c;
    x >> a;
    x.ignore();
    x >> b;
    x.ignore();
    x >> c;
    std::cout << "Result : " << a << ", " << b << ", " << c << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Result : 11, 12, 23

Example

In the following example, we are going to skip the character until the delimiter is found.

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream x("11,23,34");
    x.ignore(11, ',');
    std::string a;
    std::getline(x, a, ',');
    std::cout << "Result : " << a << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

Result : 23
istream.htm
Advertisements