首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

用ifstream打开txt文件并用vector 向其中录入数据有关问题

2012-03-24 
用ifstream打开txt文件并用vector 向其中录入数据问题#include iostream#include fstream#include ve

用ifstream打开txt文件并用vector 向其中录入数据问题
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <functional>
//#include <cmath>
#include <numeric>
using namespace std;

int main()
{
ifstream infile("F:\\vcstudy\\input.txt"); 
ofstream outfile("F:\\vcstudy\\output.txt"); 

  vector<double> vec;
double total;
infile>>total;
double number;
while(!infile.eof())
{
infile>>number;
vec.push_back(number);
}

sort(vec.begin(),vec.end());

double average=accumulate(vec.begin(),vec.end(),0.0)/(total*1.0);


outfile<<"the max number is:"<<vec.back()<<endl;
outfile<<"the min number is:"<<vec.front()<<endl;
outfile<<"the average number is:"<<average<<endl;
}

1现在要实现input.txt第一个数字200(表示数据总个数)不参与平局值计算,应该怎么改?
2还有就是sort排序输出的怎么只有6位有效数字,现在想实现输出12位?
3解释下infile>>total;两句的功能

  while(!infile.eof())
{
infile>>number;
vec.push_back(number);
}




[解决办法]
1.可以使用重定位方法 infile.seekg()
给个地址你去看用法 :http://www.cplusplus.com/
或者加个标记:
true flag = false; 第一次读了之后将flag 置true 

2.详见此帖:
http://topic.csdn.net/u/20120226/13/598bc188-2af9-4b6b-9e0f-1b8874103bc2.html?63521

3.

C/C++ code
while(!infile.eof())   //判断 是否到了文件尾{infile>>number;         //从infile流中当前标记所指值赋给number(遇空格停止)vec.push_back(number);}
[解决办法]
1.如果你第一个数字也是第一行的话,直接读到一个整数里面即可。比如int count; infile>>count;

2.c++的流是可以设置精度的。比如precision成员函数

3.从infile流读一个double到number里面

热点排行