C++ peek函数用法详解

C++ peek函数用法详解,第1张

概述peek 成员函数与 get 类似,但有一个重要的区别,当 get 函数被调用时,它将返回输入流中可用的下一个字符,并从流中移除该字符;但是,peek 函数返回下一个可用字符的副本,而不从流 peek 成员函数与 get 类似,但有一个重要的区别,当 get 函数被调用时,它将返回输入流中可用的下一个字符,并从流中移除该字符;但是,peek 函数返回下一个可用字符的副本,而不从流中移除它。

因此,get() 是从文件中读取一个字符,但 peek() 只是"看"了下一个字符而没有真正读取它。为了更好地理解这种差异,假设新打开的文件包含字符串 "abc",则以下语句序列将在屏幕上打印两个字符 "ab":

char ch = infile.get () ; // 读取一个字符
cout << ch;    //输出字符
ch = infile.get () ; // 读取另一个字符
cout << ch; //输出字符

但是,以下语句则将在屏幕上打印两个字符 "aa":

char ch = infile.peek () ; //返回下一个字符但是不读取它
cout << ch;    //输出字符
ch = infile.get () ; //现在读取下一个字符
cout << ch; //输出字符

当需要在实际阅读之前知道要读取的数据类型时,peek 函数非常有用,因为这样就可以决定使用最佳的输入方法。如果数据是数字的,最好用流提取 *** 作符 >> 读取,但如果数据是非数字字符序列,则应该用 get 或 getline 读取。

下面的程序使用 peek 函数通过将文件中出现的每个整数的值递增 1 来修改文件的副本:
// This program demonstrates the peek member function.、#include <iostream>#include <string>#include <fstream>using namespace std;int main(){    // Variables needed to read characters and numbers    char ch;    int number;    // Variables for file handling    string filename;    fstream infile,outfile;    // Open the file to be modifIEd    cout << "Enter a file name: ";    cin >> filename;    infile.open(filename.c_str(),ios::in);    if (!infile)    {        cout << "Cannot open file " << filename;        return 0;    }    // Open the file to receive the modifIEd copy    outfile.open("modifIEd.txt",ios::out);    if (!outfile)    {        cout << "Cannot open the outpur file.";        return 0;    }    // copy the input file one character at a time except numbers in the input file must have 1 added to them    // Peek at the first character    ch = infile.peek();    while (ch != EOF)    {        //examine current character        if (isdigit(ch))        {            // numbers should be read with >>            infile >> number;            outfile << number + 1;        }        else        {            // just a simple character,read it and copy it            ch = infile.get();            outfile << ch;        }        // Peek at the next character from input file        ch = infile.peek();    }    // Close the files    infile.close();    outfile.close ();    return 0;}

程序测试文件内容:
Amy is 23 years old. Robert is 50 years old. The difference between their ages is 27 years. Amy was born in 1986.
程序输出结果:
Amy is 24 years old. Robert is 51 years old. The difference between their ages is 28 years. Amy was born in 1987.

该程序事先无法知道下一个要读取的字符是一个数字还是一个普通的非数字字符(如果是数字,则应该使用流提取 *** 作符 >> 来读取整个数字;如果是字符,则应该通过调用 get() 成员函数来读取)。

因此,程序使用 peek() 来检查字符而不实际读取它们。如果下一个字符是一个数字,则调用流提取 *** 作符来读取以该字符开头的数字;否则,通过调用 get() 来读取字符并将其复制到目标文件中。
总结

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

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

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

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

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

发表评论

登录后才能评论

评论列表(0条)

    保存