peek在c语⾔中的作⽤,C++peek函数⽤法详解
peek 成员函数与 get 类似,但有⼀个重要的区别,当 get 函数被调⽤时,它将返回输⼊流中可⽤的下⼀个字符,并从流中移除该字符;但是,peek 函数返回下⼀个可⽤字符的副本,⽽不从流中移除它。
因此,get() 是从⽂件中读取⼀个字符,但 peek() 只是"看"了下⼀个字符⽽没有真正读取它。为了更好地理解这种差异,假设新打开的⽂件包含字符串 "abc",则以下语句序列将在屏幕上打印两个字符 "ab":
char ch = () ; // 读取⼀个字符
cout << ch;    //输出字符
ch = () ; // 读取另⼀个字符
cout << ch; //输出字符
但是,以下语句则将在屏幕上打印两个字符 "aa":
char ch = inFile.peek () ; //返回下⼀个字符但是不读取它
cout << ch;    //输出字符
ch = () ; //现在读取下⼀个字符
cout << ch; //输出字符
当需要在实际阅读之前知道要读取的数据类型时,peek 函数⾮常有⽤,因为这样就可以决定使⽤最佳的输⼊⽅法。如果数据是数字的,最好⽤流提取操作符 >> 读取,但如果数据是⾮数字字符序列,则应该⽤ get 或 getline 读取。
下⾯的程序使⽤ peek 函数通过将⽂件中出现的每个整数的值递增 1 来修改⽂件的副本:
// This program demonstrates the peek member function.、
#include
#include
#include
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)
{
c++中string的用法cout << "Cannot open file " << fileName;
return 0;
}
// Open the file to receive the modified copy
outFile.open("", 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 = ();
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() 来读取字符并将其复制到⽬标⽂件中。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。