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
廣告