c++ 按行读取 (getline)

来源:互联网 发布:java 图片转换base64 编辑:程序博客网 时间:2024/06/07 14:30

转自: http://blog.chinaunix.net/uid-20564678-id-3424272.html


1. filebuf::open(const char*, mode); 第一个参数表示文件,第二个参数对应打开方式,如ios::in输入
2. getline(istream &, string &, char del); 第一个参数打开的流,第二个参数保存读入的内容,第三个参数字段的分割副,默认是 '\n'
3. string::find(); 查找某一个字符在字符串中的位置

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. using namespace std;
  5. /** 读文件
  6.  */
  7. int main(int argc,char **argv)
  8. {
  9.     filebuf fb;
  10.     string filename = "test.txt";
  11.     if(fb.open(filename.c_str(),ios::in) == NULL) 
  12.     {
  13.         cout << "error" << endl;
  14.     }
  15.     istream is(&fb);
  16.     string input;
  17.     while(getline(is,input,'\n'))
  18.     {
  19.         int pos1 = string::npos;
  20.         pos1 = input.find("\t");
  21.         if(pos1 != string::npos)
  22.         {
  23.             cout << input.substr(pos1+1) << endl;
  24.         }
  25.         else
  26.         {
  27.             cout << "eror";
  28.             break;
  29.         }
  30.     }
  31.     fb.close();
  32.     return 0;
  33. }
  1. #include <iostream>  
  2. #include <fstream>  
  3.   
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.         ifstream ifs("unicode_big_endian.txt");  
  9.         string str;  
  10.         int i = 0;  
  11.         while(getline(ifs, str))  
  12.         {     
  13.                 printf("%04X\n", *(unsigned short *)str.c_str());  
  14.         }     
  15.   
  16.         return 0;  
  17. }