c++ 按行读取 (getline)

2012-11-30 12:27:23 · 作者: · 浏览: 355

    1. filebuf::open(const char*, mode); 第一个参数表示文件,第二个参数对应打开方式,如ios::in输入

    2. getline(istream &, string &, char del); 第一个参数打开的流,第二个参数保存读入的内容,第三个参数字段的分割副,默认是 '\n'

    3. string::find(); 查找某一个字符在字符串中的位置

    #include <iostream>

    #include <string>

    #include <fstream>

    using namespace std;

    /** 读文件

    */

    int main(int argc,char **argv)

    {

    filebuf fb;

    string filename = “test.txt”;

    if(fb.open(filename.c_str(),ios::in) == NULL)

    {

    cout << “error” << endl;

    }

    istream is(&fb);

    string input;

    while(getline(is,input,'\n'))

    {

    int pos1 = string::npos;

    pos1 = input.find(“\t”);

    if(pos1 != string::npos)

    {

    cout << input.substr(pos1+1) << endl;

    }

    else

    {

    cout << “eror”;

    break;

    }

    }

    fb.close();

    return 0;

    }