C++ istream get() ostream::put()

来源:互联网 发布:python redis 有效期 编辑:程序博客网 时间:2024/05/22 17:17

get()
get()函数比较灵活,有3种常用的重载形式:

一种就是和put()对应的形式:ifstream &get(char &ch);功能是从流中读取一个字符,结果保存在引用ch中,如果到文件尾,返回空字符。如file2.get(x);表示从文件中读取一个字符,并把读取的字符保存在x中。

另一种重载形式的原型是: int get();这种形式是从流中返回一个字符,如果到达文件尾,返回EOF,如x=file2.get();和上例功能是一样的。

还有一种形式的原型是:ifstream &get(char *buf,int num,char delim=’\n’);这种形式把字符读入由 buf 指向的数组,直到读入了 num 个字符或遇到了由 delim 指定的字符,如果没使用 delim 这个参数,将使用缺省值换行符’\n’。例如:

file2.get(str1,127,’A’); //从文件中读取字符到字符串str1,当遇到字符’A’或读取了127个字符时终止。

put() :Inserts character c into the stream.
ostream& put (char c);

// typewriter#include <iostream>     // std::cin, std::cout#include <fstream>      // std::ofstreamint main () {  std::ofstream outfile ("test.txt");  char ch;  std::cout << "Type some text (type a dot to finish):\n";  do {    ch = std::cin.get();    outfile.put(ch);  } while (ch!='.');  return 0;}
0 0
原创粉丝点击