C++ Ostream::tellp() 函数



C++ 的std::ostream::tellp()函数用于获取输出流中输出指针的当前位置。此位置指示下一个字符将插入的位置。该函数返回类型为std::streampos的值,表示从流开头起的偏移量。

语法

以下是std::ostream::tellp()函数的语法。

streampos tellp();

参数

它不接受任何参数。

返回值

此函数返回流中的当前位置。

异常

如果抛出异常,则对象处于有效状态。

数据竞争

它修改流对象。

示例

在下面的示例中,我们将考虑tellp()函数的基本用法。

#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;
}

输出

以上代码的输出如下:

Current position : 7

示例

考虑以下示例,我们将检查附加数据之前和之后的位置。

#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;
}

输出

以上代码的输出如下:

Position before appending : 2
Position after appending : 6

示例

让我们来看下面的例子,我们将结合使用tellp()函数和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;
}

输出

如果我们运行上面的代码,它将生成以下输出:

Result : 2
ostream.htm
广告
© . All rights reserved.