C++ istream::sync() function



The C++ std::istream::sync() function is used to synchronize the input stream with the associated input sequence. When this function is invoked, it clears the input buffer, ensuring that any unread characters are discarded and the stream is synchronized with the underlying input device.

Syntax

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

int sync();

Parameters

It does not accept any parameter.

Return Value

If the function fails, either because no stream buffer object is associated to the stream (rdbuf is null), or because the call to its pubsync member fails, it returns -1.otherwise, it returns zero, indicating success.

Exceptions

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

Data races

Modifies the stream object.

Example

In the following example, we are going to consider the basic usage of the sync() function.

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream a("Tutorials Point");
    a.sync();
    std::string b;
    a >> b;
    std::cout << "Result : " << b << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Result : Tutorials

Example

Consider the following example, where we are going to perform the synchronization with std::cin.

#include <iostream>
int main()
{
    std::cin.sync();
    std::string a;
    std::cout << "Enter Input : ";
    std::cin >> a;
    std::cout << "Welcome To , " << a << "." << std::endl;
    return 0;
}

Output

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

Enter Input : TutorialsPoint
Welcome To , TutorialsPoint.

Example

Let's look at the following example, where we are going to flush the std::cin buffer.

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream a("Hi 112");
    std::string b;
    int x;
    a >> b;
    a.sync();
    a >> x;
    std::cout << "Text: " << b << " , Number: " << x << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Text: Hi , Number: 112
istream.htm
Advertisements