大佬教程收集整理的这篇文章主要介绍了C++ peek函数用法详解,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
char ch = inFile.get () ; // 读取一个字符
cout << ch; //输出字符
ch = inFile.get () ; // 读取另一个字符
cout << ch; //输出字符
char ch = inFile.peek () ; //返回下一个字符但是不读取它
cout << ch; //输出字符
ch = inFile.get () ; //现在读取下一个字符
cout << ch; //输出字符
>>
读取,但如果数据是非数字字符序列,则应该用 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; }@H_944_19@程序测试文件内容:
该程序事先无法知道下一个要读取的字符是一个数字还是一个普通的非数字字符(如果是数字,则应该使用流提取操作符
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函数用法详解所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。