关于 文件读写 和 char



#include <iostream>     // std::cout
#include <fstream>      // std::ifstream
#include <vector>


using namespace std;


static int t;
int main () 
{
  t=0;
  cout<<"sizeof(char)="<<sizeof(char)<<endl;
  fstream f,n;
  vector<char> s;
  int length;
  f.open("test.txt",fstream::in|fstream::out|fstream::app);
  n.open("new.txt",fstream::in|fstream::out);
  if(f&&n)
  {
cout<<"success"<<endl;
f.seekg(0,f.end);
length=f.tellg();
f.seekg(0,f.beg);
cout<<"length="<<length<<endl;
  }
  else
cout<<"error"<<endl;

  char *d= new char [length];
  f.read(d,length);
  
  //for(int k=0;k<length;k++)
cout<<"d[0]= "<<d[0]<<endl;
cout<<"d[1]= "<<d[1]<<endl;
cout<<"d[2]= "<<d[2]<<endl;
cout<<"d[3]= "<<d[3]<<endl;
cout<<"d[4]= "<<d[4]<<endl;
  
  cout<<"cout.write ";
  cout.write(d,length);
  cout<<endl;
  
  for(int i=0;i<length;i++)
  {
if(d[i]!=' ') s.push_back(d[i]);
  }
  
  for(int j=0;j<s.size();j++)
  {
   cout<<"s["<<j<<"]="<<s[j]<<endl;
   t=t+((int)s[j]-48);  
   }
   
   
   cout<<"sum is "<<t<<" avage is "<<t/s.size()<<endl;
  


  n.write(d,length);
  delete[] d;

  return 0;

}

这里  要求 text.txt中  有 1 2 3 数  对其 求和 求平均值

思路是 先将 文件的直接 利用 read()读到 内存中 在 把 空格符筛选掉  放在 vector的char容器中;然后计算。

这里在调试时 出现的问题有:

1 read()只能是  char类型数据  操作  如果将new 开辟heap时  是定义的int会 报错

2 将 char 类型的 1  转换成  int类型的1  如果  (int)1=49;即1 字符的ascii 为49  我们 可以采用 (int)1-48的到int型的1;

  


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值