每个输入类 ifstream、fstream 和 istringstream 都有一个 get 系列成员函数,可用于读取单个字符,语法如下:
第一个版本读取单个字符。如果成功,则返回代表读取字符的整数代码。如果不成功,则在流上设置错误代码并返回特殊值 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);
- }