读写文件.cpp

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <functional>
#include <numeric>
#include <string>
#include <sstream> // std::istringstream
#include <bitstring.h>
using namespace std;

#define FILE_NAME "test.txt"

void strSplit(string str, const char split, vector<string> &v)
{
  istringstream iss(str);            // 输入流
  string token;                      // 接收缓冲区
  while (getline(iss, token, split)) // 以split为分隔符
  {
    // cout << token << endl; // 输出
    v.push_back(token);
  }
}

void readFile1()
{
  ifstream ifs;
  ifs.open(FILE_NAME, ios::in); // 读文件
  if (!ifs.is_open())
  {
    cout << "fail" << endl;
    return;
  }
  string buf;
  while (getline(ifs, buf))
  {
    cout << buf << endl;
  }
  ifs.close();
}
void readFile2()
{
  ifstream ifs;
  ifs.open(FILE_NAME, ios::in); // 读文件
  if (!ifs.is_open())
  {
    cout << "fail" << endl;
    return;
  }
  string buf;
  vector<string> strList;

  while (getline(ifs, buf))
  {
    strList.resize(8); 开辟空间
    cout << buf << endl;
    strSplit(buf, ' ', strList);
    cout << "\t";
    // for (vector<string>::iterator it = strList.begin(); it != strList.end(); it++)
    // {
    //   cout << *it <<"---";
    // }
    // copy(strList.begin(), strList.end(), ostream_iterator<string>(cout, " "));

    cout << endl; // 输出
    cout << "strList.size()" << strList.size() << endl;
  
    strList.clear();
    cout << "strList.size()" << strList.size() << endl;
  }

  ifs.close();
}

void writeFile()
{
  ofstream ofs;
  ofs.open(FILE_NAME, ios::app); //追加
  ofs << "张三 23 1 上海徐汇" << endl;
  ofs << "唐三 8 1 北京" << endl;
  ofs << "鲁班七号 12 1 上海徐汇" << endl;
  ofs << "貂蝉 12 1 上海徐汇" << endl;
  ofs.close();
}

void test01()
{
  // vector<string> strList;
  // string str2("This-is-a-test");
  // strSplit(str2, '-', strList); // 将子串存放到strList中
  // for(vector<string>::iterator it = strList.begin() ;it != strList.end() ;it++){
  //  cout << *it << endl; // 输出
  // }
}

int main()
{
 readFile2();
 

  // copy算法 将容器内指定范围的元素拷贝到另一容器中
 

  // for_each(vTarget.begin(), vTarget.end(), [](int val)
  //          { cout << val << " "; });
 

  cout << endl;
  // 0 1 2 3 4 5 6 7 8 9

  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值