加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:37:32 所属栏目:百科 来源:网络整理
导读:每个输入类 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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读