Sunday, July 12, 2009

Intro to C++ Problem please help!?

My inFile will be something like this





6


1 2 3 4 5 6


0 1000 1 0 -999 1


-2 1 -3 -1 2 3


-10 -30 -20 -5 -15 -50





so, the first number is the number of numbers in each line.





I have to calculate the ave, min, max and total for each line and outfile it like this;





1 2 3 4 5 6


Min: 1


Max: 6


Ave: 3.5


Total: 21





0 1000 1 0 -999 1


MIn: ....





and so on.





My problem so far is that I cant find out how to inFile the first number into a variable, then input the following numbers of each line into variables, here is what I have so far;





#include%26lt;iostream%26gt;


#include%26lt;cmath%26gt;


#include%26lt;iomanip%26gt;


#include%26lt;fstream%26gt;


using namespace std;


int main ( )





{


int j,i;





ifstream inFile;


ofstream outFile;





inFile.open("inFile.txt");


outFile.open("outFile.txt");





if((inFile.fail())||(outFile.fail()))


cout%26lt;%26lt;"Error: File open failure"%26lt;%26lt;endl;


else


{


do


{


if(j!='\n')


{


inFile%26gt;%26gt;j;


}


for(i=0; i!='\n', i%26lt;=j; i++)


{


inFile%26gt;%26gt;i;


}


cout%26lt;%26lt;setw(50)%26lt;%26lt;i%26lt;%26lt;endl;


cout%26lt;%26lt;j%26lt;%26lt;endl;


}


while(!inFile.eof());


}


return 0;


}

Intro to C++ Problem please help!?
Here is the solution





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;


#include %26lt;sstream%26gt;


#include %26lt;algorithm%26gt;


using namespace std;


ifstream inFile("inFile.txt");


#define cin inFile


ofstream outFile("outFile.txt");


#define cout outFile


int main()


{


string line;


int n,total,index;


int *elements;


cin%26gt;%26gt;n;


getline(cin,line);


elements=new int [n];


while (getline(cin,line))


{


istringstream ss(line);


index=0;


while (!ss.eof())


ss%26gt;%26gt;elements[index++];


cout%26lt;%26lt;"Min: "%26lt;%26lt;*min_element(elements,elements+n)%26lt;%26lt;en...


cout%26lt;%26lt;"Max: "%26lt;%26lt;*max_element(elements,elements+n)%26lt;%26lt;en...


total=0;


for (int j=0;j%26lt;n;j++)


total+=elements[j];


cout%26lt;%26lt;"Ave: "%26lt;%26lt;(float)total/n%26lt;%26lt;endl;


cout%26lt;%26lt;"Total: "%26lt;%26lt;total%26lt;%26lt;endl%26lt;%26lt;endl;


}


delete []elements;


return 0;


}





hope i helped u


No comments:

Post a Comment