473,320 Members | 2,088 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

fstream problem!!

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::
Expand|Select|Wrap|Line Numbers
  1. include<iostream>
  2. include<fstream>
  3. include<iomanip>
  4. using namespace std;
  5. int main ()
  6. {
  7.     ifstream infile;
  8.     ofstream outfile;
  9.     int num1,num2,num3,sum;
  10.     float aver;
  11.  
  12.     infile.open("g:\\TestIn.txt");
  13.     outfile.open("g:\\TestOut.txt");
  14.  
  15.     if (infile.fail() || outfile.fail())
  16.     {
  17.         cout<<"failed";
  18.         return 1;
  19.     }
  20. else
  21.     while(!infile.eof())
  22.     {
  23.         infile>>num1>>num2>>num3;
  24.         outfile<<num1<<num2<<num3<<endl;
  25.         sum=num1+num2+num3;
  26.     aver=sum/3;
  27.         outfile<<"Total      ="<<sum<<endl;
  28.         outfile<<"average    ="<<aver<<endl;
  29.         outfile<<"_________________\n";
  30.  
  31.     }
  32.         return 0;
  33. }
ANY IDEAS????PLS!!!!!
Nov 9 '07 #1
15 2676
Laharl
849 Expert 512MB
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.
Nov 9 '07 #2
Studlyami
464 Expert 256MB
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:

Expand|Select|Wrap|Line Numbers
  1. //you will need to include <vector>
  2.  
  3. vector<int> MyVector;
  4. int Temp = 0;
  5. int Total = 0;
  6. while(!infile.eof())
  7. {
  8.         infile>>Temp;
  9.         MyVector.push_back(Temp);
  10. } //now integers are in your vector
  11.  
  12. // loop Calculate total here. *Hint* Take a look at the vector.size() function
  13. // calculate average here.  Again look at the vector.size() function.
  14.  
Nov 9 '07 #3
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:

Expand|Select|Wrap|Line Numbers
  1. //you will need to include <vector>
  2.  
  3. vector<int> MyVector;
  4. int Temp = 0;
  5. int Total = 0;
  6. while(!infile.eof())
  7. {
  8.         infile>>Temp;
  9.         MyVector.push_back(Temp);
  10. } //now integers are in your vector
  11.  
  12. // loop Calculate total here. *Hint* Take a look at the vector.size() function
  13. // calculate average here.  Again look at the vector.size() function.
  14.  
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
Nov 9 '07 #4
i rewrote the code to:

Expand|Select|Wrap|Line Numbers
  1. ifstream infile;
  2.     ofstream outfile;
  3.     float num1,num2,limit=0,counter=0,sum=0,aver=0;
  4.  
  5.  
  6.     infile.open("g:\\TestIn.txt");
  7.     outfile.open("g:\\TestOut.txt");
  8.  
  9.     if (infile.fail() || outfile.fail())
  10.     {
  11.         cout<<"failed";
  12.         return 1;
  13.     }
  14. else
  15.     while(!infile.eof())
  16.     {
  17.         infile>>num1;
  18.         limit=num1;
  19.         while(counter<limit)
  20.         {
  21.             infile>>num2;
  22.         outfile<<num2;
  23.         sum+=num2;
  24.         counter++;
  25.         }
  26.  
  27.     }        
  28.     outfile<<"\nTotal      ="<<sum<<endl;
  29.     aver=sum/counter;
  30.     outfile<<"average  ="<<aver;
  31.         return 0;
  32. }
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
Nov 9 '07 #5
Studlyami
464 Expert 256MB
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
Expand|Select|Wrap|Line Numbers
  1. int sum = 0;
  2. int Temp = 0;
  3. int TotalItems = 0; //to keep track of the numbers inputed.
  4. while(!infile.eof())
  5. {
  6.     infile>>Temp;
  7.     outfile<<Temp;
  8.  
  9.     sum += Temp; //this is the same as "sum = sum + Temp;"
  10.         TotalItems++; //adds one to total items
  11. }
  12.  
  13.     aver=sum/TotalItems;
  14.  
  15. //Your outfile doesn't have any <<endl in it, but you could add some logic to add a new line based upon TotalItems
  16.         outfile<<"Total      ="<<sum<<endl;
  17.         outfile<<"average    ="<<aver<<endl;
  18.         outfile<<"_________________\n";
  19.  
  20.  
  21.         return 0;
  22. }
Ahh for grabbing the second line take a look at the getline function of the fstream.
Nov 9 '07 #6
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
Expand|Select|Wrap|Line Numbers
  1. int sum = 0;
  2. int Temp = 0;
  3. int TotalItems = 0; //to keep track of the numbers inputed.
  4. while(!infile.eof())
  5. {
  6.     infile>>Temp;
  7.     outfile<<Temp;
  8.  
  9.     sum += Temp; //this is the same as "sum = sum + Temp;"
  10.         TotalItems++; //adds one to total items
  11. }
  12.  
  13.     aver=sum/TotalItems;
  14.  
  15. //Your outfile doesn't have any <<endl in it, but you could add some logic to add a new line based upon TotalItems
  16.         outfile<<"Total      ="<<sum<<endl;
  17.         outfile<<"average    ="<<aver<<endl;
  18.         outfile<<"_________________\n";
  19.  
  20.  
  21.         return 0;
  22. }
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
Expand|Select|Wrap|Line Numbers
  1. 6(number of # per line)
  2. 1 2 3 4 5 6 
  3. -1 -2 -3 -4 -5 -6 
  4. and so on
output be like
Expand|Select|Wrap|Line Numbers
  1. 1 2 3 4 5 6
  2. sum=the sum
  3. aver=the aver
  4. -1 -2 -3 -4 -5 -6
  5. sum=the sum
  6. aver=the aver
  7. and so on
  8.  
???????
Nov 9 '07 #7
Studlyami
464 Expert 256MB
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.
Expand|Select|Wrap|Line Numbers
  1. while(<file>!=eof())
  2. {
  3.      getline(. . .)
  4.      char *characterHolder = strtok(<char array from getline>, " ")
  5.      while (characterHolder !=NULL)
  6.      {
  7.          sum += atoi(. . . );
  8.          characterHolder = strtok (NULL, " ");
  9.      } 
  10. }
  11.  
Nov 10 '07 #8
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.
Expand|Select|Wrap|Line Numbers
  1. while(<file>!=eof())
  2. {
  3.      getline(. . .)
  4.      char *characterHolder = strtok(<char array from getline>, " ")
  5.      while (characterHolder !=NULL)
  6.      {
  7.          sum += atoi(. . . );
  8.          characterHolder = strtok (NULL, " ");
  9.      } 
  10. }
  11.  
WOW I DIDNT UNDERSTAND NOTHING!!!!!!!IM STUPID!!!!!!
Nov 10 '07 #9
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?
Nov 10 '07 #10
Laharl
849 Expert 512MB
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:
Expand|Select|Wrap|Line Numbers
  1. int sum, count;
  2. ifstream in;
  3. ofstream out;
  4. in.open("infile.txt");
  5. out.open("outfile.txt");
  6. if (!in || !out)
  7.     cout << "ERROR" << endl;
  8. while (!in.eof()){
  9.     int a = 0;
  10.     in >> a;
  11.     out << a;
  12.     sum += a;
  13.     count++;
  14. }
  15.  
This takes all of the numbers from the input file, sums them, counts them, and outputs them to the output file.
Nov 10 '07 #11
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:
Expand|Select|Wrap|Line Numbers
  1. int sum, count;
  2. ifstream in;
  3. ofstream out;
  4. in.open("infile.txt");
  5. out.open("outfile.txt");
  6. if (!in || !out)
  7.     cout << "ERROR" << endl;
  8. while (!in.eof()){
  9.     int a = 0;
  10.     in >> a;
  11.     out << a;
  12.     sum += a;
  13.     count++;
  14. }
  15.  
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!!!!
Nov 10 '07 #12
Studlyami
464 Expert 256MB
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.
Nov 10 '07 #13
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
Expand|Select|Wrap|Line Numbers
  1. 2 3       2>>>number of lines         3>>>number of #s per line
  2. 1 2 3
  3. 4 5 6
  4. or
  5. 3 2
  6. 1 2
  7. 3 4
  8. 5 6
  9. AND SO ON....
  10.  
this will work for any input file but you have to chane the top number as well
the code is
Expand|Select|Wrap|Line Numbers
  1. int main ()
  2. {
  3.     ifstream infile;
  4.     ofstream outfile;
  5.     float num1,num2,num3,limit1=0,limit2=0,counter1=0,counter2=0,sum=0;
  6.     float aver;
  7.  
  8.     infile.open("testin.txt");
  9.     outfile.open("testout.txt");
  10.  
  11.     if (infile.fail() || outfile.fail())
  12.     {
  13.         cout<<"failed";
  14.         return 1;
  15.     }
  16. else
  17.     while(!infile.eof())
  18.     {
  19.         infile>>num1>>num2;
  20.         limit1=num1;
  21.         limit2=num2;
  22.         while(counter1<limit1)
  23.         {
  24.         sum=0;
  25.         counter2=0;
  26.  
  27.         while (counter2<limit2)
  28.         {
  29.             infile>>num3;
  30.             outfile<<num3<<" ";
  31.             sum+=num3;
  32.             counter2++;
  33.         }
  34.         outfile<<"\nTotal      ="<<sum<<endl;
  35.         aver=sum/limit2;
  36.         outfile<<"Average    ="<<aver<<endl;
  37.         outfile<<"____________________"<<endl;
  38.         counter1++;
  39.  
  40.         }
  41.  
  42.     }
  43.  
  44.         return 0;
  45. }
BUT NOW I NEED TO GET THE MIN AND MAX OF EACH LINE!!!
can you please help me to do it????
Nov 10 '07 #14
Studlyami
464 Expert 256MB
you already have a thread for that so let us keep it in that thread.
Nov 10 '07 #15
you already have a thread for that so let us keep it in that thread.
ok tanx anyway for all the helps
Nov 10 '07 #16

Sign in to post your reply or Sign up for a free account.

Similar topics

1
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()...
5
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...
6
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();
3
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...
3
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>...
0
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...
5
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: ...
6
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;
3
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...
0
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...
0
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...
0
isladogs
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...
1
isladogs
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...
0
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...
0
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...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
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....
0
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.