C++文件读取和写入操作的方法:
1、使用“<<” 和“>>” 操作符;
2、使用“istream::read” 和"ostream::write"方法;
3、使用“istream::get”和“ostream::put”方法;
今天我用的是"<<"和“>>”方式:
一、相关代码
#include<fstream>
#include<iostream>
#include<iomanip>
int main(int argc, char *argv[])
{
std::ifstream ifs("A.txt", std::ios::in);
if(!ifs.is_open())
{
std::cerr << "open file failed..." << std::endl;
return 0;
}
double sum = 0;
int count = 0;
while(!ifs.eof())
{
double n = 0;
ifs >> n;
sum += n;
count++;
std::cout << std::setprecision(9) << n <<std::endl;
}
ifs.close();
std::ofstream ofs("B.txt", std::ios::out);
if(!ofs.is_open())
{
std::cerr << "open file failed..." << std::endl;
return 0;
}
ofs << "sum:" << std::setprecision(9) << sum <<std::endl
<< "ave:" << std::setprecision(9) << sum / (double)count << std::endl;
ofs.close();
return 0;
}
二、运行结果
其中A.txt中的数字是用 excel表格的RAND() *100生成的