C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C++ get函数用法完全攻略大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
每个输入类 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;
}@H_772_11@
此程序将显示任何文件内容。由于 get 函数不会跳过白色空格,因此所有字符都将按照文件中的出现方式显示

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

大佬总结

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

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: