学习C++ peek函数用法详解(转)

本文探讨了C++中peek和get成员函数的区别,peek函数允许预览输入流中的下一个字符而不移除它,这对于确定数据类型并选择合适的读取方法非常有用。通过一个示例程序,展示了如何使用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 读取。

// 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.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值