C++按行读写文件(getline函数的用法)

C++ 中有两个 getline() 函数 (1)一个是全局函数,在 string 类中定义(#include<string>),但并不是 string 类的成员函数,原型如下: istream& getline( istream& is, string& s, char delimiter = '\n' );

使用方法如下:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

void main()
{
  ifstream fin;//输入流
  fin.open("D:\\test.txt");//注意路径的写法,由于\是转义字符,所以路径中\\代表\
  string str;//接收字符串
  while(getline(fin,str))//一行一行读
  {
     cout<<str<<endl;
  }
}

(2)另一个是 istream 类的成员函数,原型如下: istream& getline( char* buffer, streamsize num ); istream& getline( char* buffer, streamsize num, char delim );

使用方法如下:

#include<iostream>
#include<fstream>
using namespace std;

void main()
{
  ifstream fin;//输入流
  fin.open("D:\\test.txt");//注意路径的写法,由于\是转义字符,所以路径中\\代表\
  char * buffer;//缓冲区
  buffer=(char *)malloc(100*sizeof(char));//分配空间
  while(!fin.eof())//一行一行读
  {
     fin.getline(buffer,n,delim);//读n-1个字符到buffer,直到碰到换行或EOF或delim
  }
}