C++ Ostream::tellp() function



The C++ std::ostream::tellp() function is used to obtain the current position of the put pointer in an output stream. This position indicates where the next character will be inserted. The function returns a value of type std::streampos, representing the offset from the beginning of the stream.

Syntax

Following is the syntax for std::ostream::tellp() function.

streampos tellp();

Parameters

It does not accept any parameter.

Return Value

This function returns the current position in the stream.

Exceptions

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

Data races

It modifies the stream object.

Example

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

#include <iostream>
#include <sstream>
int main()
{
    std::stringstream a;
    a << "Welcome";
    std::streampos b = a.tellp();
    std::cout << "Current position : " << b << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Current position : 7

Example

Consider the following example, where we are going to check position before and after appending data.

#include <iostream>
#include <sstream>
int main()
{
    std::stringstream a;
    a << "Hi";
    std::streampos x = a.tellp();
    a << 1134;
    std::streampos y = a.tellp();
    std::cout << "Position before appending : " << x << std::endl;
    std::cout << "Position after appending : " << y << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Position before appending : 2
Position after appending : 6

Example

Let's look at the following example, where we are going to use the tellp() function along with the seekp().

#include <iostream>
#include <sstream>
int main()
{
    std::stringstream a;
    a << "Hi";
    std::streampos pos = a.tellp();
    a.seekp(0);
    a << "Namaste";
    std::cout << "Result : " << pos << std::endl;
    return 0;
}

Output

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

Result : 2
ostream.htm
Advertisements