C++ get函数用法完全攻略
每个输入类 ifstream、fstream 和 istringstream 都有一个 get 系列成员函数,可用于读取单个字符,语法如下:
下面的程序使用 get 函数将文件复制到屏幕上。当 get() 返回
get 的第二个版本是釆用一个字符变量的引用来读取并返回读取到的数据流。如果使用此版本的函数,则必须测试流以确定操作是否成功。如果用下面的代码替换上面程序中的第 24〜29 行,那么其表现并不会改变。
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); }
C语言/C++交流群:664104694(我们会不定期在群内分享C/C++知识,上传C/C++资料)
编程帮,一个分享编程知识的公众号。跟着站长一起学习,每天都有进步。
通俗易懂,深入浅出,一篇文章只讲一个知识点。
文章不深奥,不需要钻研,在公交、在地铁、在厕所都可以阅读,随时随地涨姿势。
文章不涉及代码,不烧脑细胞,人人都可以学习。
当你决定关注「编程帮」,你已然超越了90%的程序员!

微信扫描二维码关注
所有教程
- socket
- C#
- Python
- MySQL函数
- MySQL
- C语言入门
- C语言专题
- C语言编译器
- C语言编程实例
- GCC
- 数据结构
- C语言项目案例
- C++
- OpenCV
- Qt教程
- Unity 3D
- UE4
- STL
- Redis
- JavaScript
- PHP
- HBase
- NoSQL
- MongoDB
- MATLAB
- Markdown
- Android教程
- vi命令
- TCP/IP
- Spring MVC
- Mybatis
- Hibernate
- Spring Boot
- Maven
- Spring Cloud
- Linux
- Linux命令
- Shell
- Java教程
- 设计模式
- Spring
- Servlet
- Struts2
- Java Swing
- JSP教程
- CSS教程
- TensorFlow
- 区块链
- Go语言
- Docker
- 编程笔记
- 资源下载
- 关于我们
- 汇编语言
- 大数据
- 云计算
- VIP视频