C++ get函数用法完全攻略

C++ get函数用法完全攻略,第1张

概述每个输入类 ifstream、fstream 和 istringstream 都有一个 get 系列成员函数,可用于读取单个字符,语法如下: int get(); istream get(char c); 第一个版本读取单个字符。如果成功,则返回代表读取字 每个输入类 ifstream、fstream 和 istringstream 都有一个 get 系列成员函数,可用于读取单个字符,语法如下:

int get();
istream& get(char& c);

第一个版本读取单个字符。如果成功,则返回代表读取字符的整数代码。如果不成功,则在流上设置错误代码并返回特殊值 EOF

下面的程序使用 get 函数将文件复制到屏幕上。当 get() 返回 EOF 时,第 24〜29 行的循环终止。
// This program demonstrates the use of the get member// functions of the istream class#include <iostream>#include <string>#include <fstream>using namespace std;int main(){    //Variables needed to read file one character at a time    string filename;    fstream file;    char ch; // character read from the file    // Get file name and open file    cout << "Enter a file name: ";    cin >> filename;    file.open(filename,ios::in);    if (!file)    {        cout << filename << " Could not be opened .\n";        return 0;    }    // Read file one character at a time and echo to screen    ch = file.get ();    while (ch != EOF)    {        cout << ch;        ch = file.get();    }    // Close file    file.close ();    return 0;}
此程序将显示任何文件的内容。由于 get 函数不会跳过白色空格,因此所有字符都将按照文件中的出现方式显示。

get 的第二个版本是釆用一个字符变量的引用来读取并返回读取到的数据流。如果使用此版本的函数,则必须测试流以确定 *** 作是否成功。如果用下面的代码替换上面程序中的第 24〜29 行,那么其表现并不会改变。
file.get(ch);while (!file.fail ()){    cout << ch;    file.get(ch);}
总结

以上是内存溢出为你收集整理的C++ get函数用法完全攻略全部内容,希望文章能够帮你解决C++ get函数用法完全攻略所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1231170.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存