#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;