fstream问题!! [英] fstream problem!!

查看:83
本文介绍了fstream问题!!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个从输入文件(TestIn.txt)读取的代码并计算总和和平均值并将其输出到另一个文件(TestOut.txt)。

i编写代码使用每行三个数字的输入文件可以正常工作。

但我想以一种读取数据的方式编写并计算任何输入文件的总和和平均值。


我的输入是一个txt文件,比如

4 5 6

-2 -1 -3

我的输出文件现在在:

456

总计= 15

平均= 5

_________________

- 2-1-3

总计= -6

平均值= -2

_________________


i我的程序可以读取任何其他输入,例如

4 5 6 7 8 9

-4 -5 -6 -7 -8 -9

和输出:

4 5 6 7 8 9

总计= 39

平均值= 6.5

_________________

-4 -5 -6 -7 -8 -9

总计= -39

Ave rage = -6.5

我的代码是::

i have to write a code that reads from an input file (TestIn.txt) and calculates the sum and the average and output it into another file (TestOut.txt).
i wrote the code that works fine with an input file of three number per line.
But i wanna write in a way that reads data and calculate the sum and average from any input file.

my input is a txt file like
4 5 6
-2 -1 -3
my output file now in like:
456
Total =15
average =5
_________________
-2-1-3
Total =-6
average =-2
_________________

i wan to my program to be able to read from any other input like
4 5 6 7 8 9
-4 -5 -6 -7 -8 -9
and output:
4 5 6 7 8 9
Total =39
Average =6.5
_________________
-4 -5 -6 -7 -8 -9
Total =-39
Average =-6.5
my code is::

展开 | 选择 | Wrap | 行号

推荐答案

尝试输入数组,或者更好的是,像矢量一样动态调整大小的结构。输入到int,push_back(),然后再次输入。
Try inputting to an array, or better, a dynamically sized structure like a vector. Input to an int, push_back(), then input to it again.


是的,而不是让一定数量的项目看一下矢量容器。您的循环将一次抓取一个数字,将其添加到向量,然后检查是否到达文件末尾。然后在while循环之外进行计算。因此,在将所有项目添加到矢量后,设置一个循环来逐步浏览矢量以获取总数。


EX:

yeah rather than having a set number of items take a look at the vector container. Your loop will grab one number at a time, add it to the vector, and then check to see if you reach the end of file. Then do your calculations outside of the while loop. So after you have added all items to your vector set up a loop to step through your vector to grab total.

EX:

展开 | 选择 | < span class =codeLinkonclick =WordWrap(this);> Wrap | 行号



是的,而不是让一定数量的项目看一下矢量容器。您的循环将一次抓取一个数字,将其添加到向量,然后检查是否到达文件末尾。然后在while循环之外进行计算。因此,在将所有项目添加到矢量后,设置一个循环来逐步浏览矢量以获取总数。


EX:

yeah rather than having a set number of items take a look at the vector container. Your loop will grab one number at a time, add it to the vector, and then check to see if you reach the end of file. Then do your calculations outside of the while loop. So after you have added all items to your vector set up a loop to step through your vector to grab total.

EX:

展开 | 选择 | < span class =codeLinkonclick =WordWrap(this);> Wrap | 行号


这篇关于fstream问题!!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆