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:: -
include<iostream>
-
include<fstream>
-
include<iomanip>
-
using namespace std;
-
int main ()
-
{
-
ifstream infile;
-
ofstream outfile;
-
int num1,num2,num3,sum;
-
float aver;
-
-
infile.open("g:\\TestIn.txt");
-
outfile.open("g:\\TestOut.txt");
-
-
if (infile.fail() || outfile.fail())
-
{
-
cout<<"failed";
-
return 1;
-
}
-
else
-
while(!infile.eof())
-
{
-
infile>>num1>>num2>>num3;
-
outfile<<num1<<num2<<num3<<endl;
-
sum=num1+num2+num3;
-
aver=sum/3;
-
outfile<<"Total ="<<sum<<endl;
-
outfile<<"average ="<<aver<<endl;
-
outfile<<"_________________\n";
-
-
}
-
return 0;
-
}
ANY IDEAS????PLS!!!!!
15 2676
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.
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: -
//you will need to include <vector>
-
-
vector<int> MyVector;
-
int Temp = 0;
-
int Total = 0;
-
while(!infile.eof())
-
{
-
infile>>Temp;
-
MyVector.push_back(Temp);
-
} //now integers are in your vector
-
-
// loop Calculate total here. *Hint* Take a look at the vector.size() function
-
// calculate average here. Again look at the vector.size() function.
-
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: -
//you will need to include <vector>
-
-
vector<int> MyVector;
-
int Temp = 0;
-
int Total = 0;
-
while(!infile.eof())
-
{
-
infile>>Temp;
-
MyVector.push_back(Temp);
-
} //now integers are in your vector
-
-
// loop Calculate total here. *Hint* Take a look at the vector.size() function
-
// calculate average here. Again look at the vector.size() function.
-
ok but you know i am a begginer in c++ and it a assignment.so i havent learned vector yet. can you gys give me a simple suggestion
i rewrote the code to: -
ifstream infile;
-
ofstream outfile;
-
float num1,num2,limit=0,counter=0,sum=0,aver=0;
-
-
-
infile.open("g:\\TestIn.txt");
-
outfile.open("g:\\TestOut.txt");
-
-
if (infile.fail() || outfile.fail())
-
{
-
cout<<"failed";
-
return 1;
-
}
-
else
-
while(!infile.eof())
-
{
-
infile>>num1;
-
limit=num1;
-
while(counter<limit)
-
{
-
infile>>num2;
-
outfile<<num2;
-
sum+=num2;
-
counter++;
-
}
-
-
}
-
outfile<<"\nTotal ="<<sum<<endl;
-
aver=sum/counter;
-
outfile<<"average ="<<aver;
-
return 0;
-
}
but now if my input file is
6(number of # per line)
1 2 3 4 5 6
-1 -2 -3 -4 -5 -6
the output file is like
123456
Total =21
average =3.5
i mean it doesnt include the second line just the first one!!
i need a hint or suggestion how to include the second or third or...lines
Sorry about that vectors are pretty simple to use if you want to go above and beyond Here is a reference .
We could also do it like this -
int sum = 0;
-
int Temp = 0;
-
int TotalItems = 0; //to keep track of the numbers inputed.
-
while(!infile.eof())
-
{
-
infile>>Temp;
-
outfile<<Temp;
-
-
sum += Temp; //this is the same as "sum = sum + Temp;"
-
TotalItems++; //adds one to total items
-
}
-
-
aver=sum/TotalItems;
-
-
//Your outfile doesn't have any <<endl in it, but you could add some logic to add a new line based upon TotalItems
-
outfile<<"Total ="<<sum<<endl;
-
outfile<<"average ="<<aver<<endl;
-
outfile<<"_________________\n";
-
-
-
return 0;
-
}
Ahh for grabbing the second line take a look at the getline function of the fstream.
Sorry about that vectors are pretty simple to use if you want to go above and beyond Here is a reference .
We could also do it like this -
int sum = 0;
-
int Temp = 0;
-
int TotalItems = 0; //to keep track of the numbers inputed.
-
while(!infile.eof())
-
{
-
infile>>Temp;
-
outfile<<Temp;
-
-
sum += Temp; //this is the same as "sum = sum + Temp;"
-
TotalItems++; //adds one to total items
-
}
-
-
aver=sum/TotalItems;
-
-
//Your outfile doesn't have any <<endl in it, but you could add some logic to add a new line based upon TotalItems
-
outfile<<"Total ="<<sum<<endl;
-
outfile<<"average ="<<aver<<endl;
-
outfile<<"_________________\n";
-
-
-
return 0;
-
}
Ahh for grabbing the second line take a look at the getline function of the fstream.
as i see this code is to calculate sum and average for all # in any input file
i wan it to calculate the sum and average for each line separatly.
like when input file is -
6(number of # per line)
-
1 2 3 4 5 6
-
-1 -2 -3 -4 -5 -6
-
and so on
output be like -
1 2 3 4 5 6
-
sum=the sum
-
aver=the aver
-
-1 -2 -3 -4 -5 -6
-
sum=the sum
-
aver=the aver
-
and so on
-
???????
I know of a way of doing this, but it isn't easy or pretty perhaps someone here has a better way of doing it. My way requires using the getline function to take the text in the file and add it to a character array. Then you Tokenize the character array with strtok(this function seems to be unpopular) to grab an integer. Then use the atoi function to convert the char array grabbed from the strtok function and add it to sum. use the counter as stated above to get total items.
AGAIN! THIS is probably not the best way of doing this, but it will work.
Also you will need to lookup some of those functions i can't remember the exact parameters to pass to them off the top of my head. -
while(<file>!=eof())
-
{
-
getline(. . .)
-
char *characterHolder = strtok(<char array from getline>, " ")
-
while (characterHolder !=NULL)
-
{
-
sum += atoi(. . . );
-
characterHolder = strtok (NULL, " ");
-
}
-
}
-
I know of a way of doing this, but it isn't easy or pretty perhaps someone here has a better way of doing it. My way requires using the getline function to take the text in the file and add it to a character array. Then you Tokenize the character array with strtok(this function seems to be unpopular) to grab an integer. Then use the atoi function to convert the char array grabbed from the strtok function and add it to sum. use the counter as stated above to get total items.
AGAIN! THIS is probably not the best way of doing this, but it will work.
Also you will need to lookup some of those functions i can't remember the exact parameters to pass to them off the top of my head. -
while(<file>!=eof())
-
{
-
getline(. . .)
-
char *characterHolder = strtok(<char array from getline>, " ")
-
while (characterHolder !=NULL)
-
{
-
sum += atoi(. . . );
-
characterHolder = strtok (NULL, " ");
-
}
-
}
-
WOW I DIDNT UNDERSTAND NOTHING!!!!!!!IM STUPID!!!!!!
one more thing i just realized that in addition of finding sum and aver i have to find the minimum and maximum valuse in each line.
i just wanna know the formula to find min and max between some num such as
1 2 3 4 5 6 or 43 7 98 0 89 any ideas?
Don't feel stupid, strtok() is pretty complicated at first glance and takes some use to get accustomed to, as it's pretty finicky.
If you don't feel up to vectors, you can use a couple integers to handle the sum and total number of inputs and then when you input something, output it straight to the file.
For example: -
int sum, count;
-
ifstream in;
-
ofstream out;
-
in.open("infile.txt");
-
out.open("outfile.txt");
-
if (!in || !out)
-
cout << "ERROR" << endl;
-
while (!in.eof()){
-
int a = 0;
-
in >> a;
-
out << a;
-
sum += a;
-
count++;
-
}
-
This takes all of the numbers from the input file, sums them, counts them, and outputs them to the output file.
Don't feel stupid, strtok() is pretty complicated at first glance and takes some use to get accustomed to, as it's pretty finicky.
If you don't feel up to vectors, you can use a couple integers to handle the sum and total number of inputs and then when you input something, output it straight to the file.
For example: -
int sum, count;
-
ifstream in;
-
ofstream out;
-
in.open("infile.txt");
-
out.open("outfile.txt");
-
if (!in || !out)
-
cout << "ERROR" << endl;
-
while (!in.eof()){
-
int a = 0;
-
in >> a;
-
out << a;
-
sum += a;
-
count++;
-
}
-
This takes all of the numbers from the input file, sums them, counts them, and outputs them to the output file.
right but just as i said
iwant to calculate the sum and average for every line separatly.
if there is to line there should be one sum and average for first line and one for second line!!!!
Alenik, I'll try to clarify my example, but I'm at work.. Laharl he needs to do the sum and average on a per line basis. I don't know how to do this without strtok :( Ill try to post up some examples to clarify my example given above when i get home from work, or some time tomorrow.
Alenik, I'll try to clarify my example, but I'm at work.. Laharl he needs to do the sum and average on a per line basis. I don't know how to do this without strtok :( Ill try to post up some examples to clarify my example given above when i get home from work, or some time tomorrow.
Ive got it all figured out
the input file is like FOR EXAMPLE -
2 3 2>>>number of lines 3>>>number of #s per line
-
1 2 3
-
4 5 6
-
or
-
3 2
-
1 2
-
3 4
-
5 6
-
AND SO ON....
-
this will work for any input file but you have to chane the top number as well
the code is -
int main ()
-
{
-
ifstream infile;
-
ofstream outfile;
-
float num1,num2,num3,limit1=0,limit2=0,counter1=0,counter2=0,sum=0;
-
float aver;
-
-
infile.open("testin.txt");
-
outfile.open("testout.txt");
-
-
if (infile.fail() || outfile.fail())
-
{
-
cout<<"failed";
-
return 1;
-
}
-
else
-
while(!infile.eof())
-
{
-
infile>>num1>>num2;
-
limit1=num1;
-
limit2=num2;
-
while(counter1<limit1)
-
{
-
sum=0;
-
counter2=0;
-
-
while (counter2<limit2)
-
{
-
infile>>num3;
-
outfile<<num3<<" ";
-
sum+=num3;
-
counter2++;
-
}
-
outfile<<"\nTotal ="<<sum<<endl;
-
aver=sum/limit2;
-
outfile<<"Average ="<<aver<<endl;
-
outfile<<"____________________"<<endl;
-
counter1++;
-
-
}
-
-
}
-
-
return 0;
-
}
BUT NOW I NEED TO GET THE MIN AND MAX OF EACH LINE!!!
can you please help me to do it????
you already have a thread for that so let us keep it in that thread.
you already have a thread for that so let us keep it in that thread.
ok tanx anyway for all the helps
Sign in to post your reply or Sign up for a free account.
Similar topics
by: las |
last post by:
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
int main()
{
string token1 = "Hello\nall";
fstream newfile("C:/temp/test1.txt", ios::trunc);
if ( newfile.good()...
|
by: jbruno4000 |
last post by:
I'm having 2 problems and hope you can help:
Fist Problem: Please see the code segment bellow. For this application I need
to access an input file and also an output file, however, when I include...
|
by: David Briggs |
last post by:
I am using MS VC++ 6.0 with MFC
I have a simple class:
#include <fstream.h>
class Data
{
public:
CString WriteStr();
Data();
|
by: David Blasdell |
last post by:
This appears very strange to me, I'm having a problem with a fstream object
inside a class which is not being called directly from main (another class
calls the class that contains the fstream...
|
by: ratzeel |
last post by:
The following snippet code throws an error while compiling on SUN os..
Any idea how to resolve this...
#include <iostream.h>
#include <fstream.h>
#include <math.h>
#include <algorithm>...
|
by: JackRazz |
last post by:
I'm trying to serialize a collection to a file stream by serializing each object
individually. The code below works fine with the BinaryFormatter, but the
SoapFormatter reads the first object and...
|
by: Simon Verona |
last post by:
I have a pair of functions that I'm calling using remoting - called readfile
and writefile.
The readfile works fine when called from the client PC.
The writefile method returns an error:
...
|
by: wiso |
last post by:
My problem is this (from:
http://www.cplusplus.com/ref/iostream/fstream/open.html)
#include <fstream>
using namespace std;
int main()
{
fstream f;
|
by: darklunar |
last post by:
Ok this is the homework problem I have to do:
Write a program to read through a file of numbers and calculate how many are positive and how many negative. Include a structure chart as in the...
|
by: DolphinDB |
last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation.
Take...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
| |