getline函数的用法

来源:互联网 发布:java文件上传实现原理 编辑:程序博客网 时间:2024/04/29 21:02
语法: 
  istream &getline( char *buffer, streamsize num );
  istream &getline( char *buffer, streamsize num, char delim );

getline()函数用于输入流,读取字符到buffer中,直到下列情况发生: 

num - 1个字符已经读入, 
碰到一个换行标志,
碰到一个EOF, 

或者,任意地读入,直到读到字符delim。delim字符不会被放入buffer中。(delim字符可以自已设定,默认为回车符'/n' ) 

举例:

#include <iostream.h>
#include<stdlib.h>
#include <iomanip.h>
#include <fstream.h>

const int N=10;
int main()
{

char str[N];
   ifstream fin;
    fin.open("data.txt");
  if (!fin)
  {
   cout<<"error "<<endl;
   exit(1);
  }
  while(fin.getline(str, sizeof(str)))//这里是从"文件"读取sizeof(str)长度的字符到 数组str中,

//当然也可以从"控制台"读取,此时为cin.getline(str, sizeof(str)).
  {
  cout<<str;
   cout<<endl;
  }
  cout<<endl;

fin.clear();
cin.get();
  return 0;
}