📜  C ++中的Tellg和Tellp之间的区别

📅  最后修改于: 2021-05-31 22:42:54             🧑  作者: Mango

在本文中,我们将讨论basic_istream <> :: tellgbasic_ostream <> :: tellp的功能以及它们之间的区别。

tellg() 该函数在istream类中定义,并与输入流一起使用。它返回当前字符在输入流中的位置。

句法:

pos_type tellg(); 

返回类型:如果指针指向有效位置,则此函数返回get指针的当前位置。否则,返回“ -1”

程序1:

下面是C++程序,用于说明tellg()的用法:

C++
// C++ program to illustrate the
// use of tellg()
#include 
#include 
using namespace std;
  
// Driver Code
int main()
{
    ifstream fin;
    char ch;
  
    // Opens the existing file
    fin.open("gfg.text");
  
    int pos;
    pos = fin.tellg();
    cout << pos;
  
    fin >> ch;
    pos = fin.tellg();
    cout << pos;
  
    fin >> ch;
    pos = fin.tellg();
    cout << pos;
  
    return 0;
}


C++
// C++ program illustrating the
// use of tellp()
#include 
#include 
using namespace std;
  
// Driver Code
int main()
{
    ofstream fout;
    char ch;
  
    // Opening the already existing file
    fout.open("gfg.text", ios::app);
    int pos;
    pos = fout.tellp();
    cout << pos;
  
    fout << "print it";
    pos = fin.tellp();
    cout << pos;
    fout.close();
  
    return 0;
}


输入文件:

gfg.text
 
 hello students

输出:

tellp() 该函数在ostream类中定义,并与输出流一起使用。它返回当前字符在输出流中可以放置字符的位置。

句法:

pos_type tellp();

返回类型:如果指针指向有效位置,则此函数返回get指针的当前位置。否则,返回“ -1”

程式2:

下面是说明使用tellp()的C++程序:

C++

// C++ program illustrating the
// use of tellp()
#include 
#include 
using namespace std;
  
// Driver Code
int main()
{
    ofstream fout;
    char ch;
  
    // Opening the already existing file
    fout.open("gfg.text", ios::app);
    int pos;
    pos = fout.tellp();
    cout << pos;
  
    fout << "print it";
    pos = fin.tellp();
    cout << pos;
    fout.close();
  
    return 0;
}

输入文件:

gfg.text

hello students
print it 

输出:

tellp()和tellg()之间的表格格式差异

tellp() tellg()
This function is used with output streams and returns the current “put” position of the pointer in the stream. The function is used with input streams and returns the current “get” position of the pointer in the stream.
Syntax: pos_type tellp(); Syntax: pos_type tellg();
It returns the position of the current character in the output stream. It returns the position of the current character in the input stream.
tellp() gives the position of the put pointer. tellg() gives the position of the get pointer.
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”