matlab的get函数的用法,C++ get函数用法完全攻略

每个输入类 ifstream、fstream 和 istringstream 都有一个 get 系列成员函数,可用于读取单个字符,语法如下:

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

#include

#include

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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值