Saturday, May 22, 2010

C++ program question?

this program is not outputting the output file, any ideas why?





#include%26lt;iostream%26gt;


#include%26lt;fstream%26gt;


#include%26lt;iomanip%26gt;





using namespace std;





int main()


{


// Declare and initialize variables //





int femaleCount;


int maleCount;


double studentGpa;


double sumFemalegpa;


double sumMalegpa;


double averageFemalegpa = sumFemalegpa / femaleCount;


double averageMalegpa = sumMalegpa / maleCount;


char femaleStudents;


char maleStudents;


char studentGender;





ifstream infile;


ofstream outfile;





infile.open("C:\\ch5_ex17data.txt");





if (!infile)


{


cout %26lt;%26lt; "Cannot opent the input file." %26lt;%26lt; endl;


cout %26lt;%26lt; "Program terminates!!!" %26lt;%26lt; endl;


return 0;


}





outfile.open("C:\\ch5_ex17.out");





outfile %26lt;%26lt; fixed %26lt;%26lt; showpoint;


outfile %26lt;%26lt; setprecision(2);





cout %26lt;%26lt; "Processing data" %26lt;%26lt; endl;





infile %26gt;%26gt; studentGender %26gt;%26gt; studentGpa;





while(infile)


{


switch(studentGender)


{


case 'f':


studentGpa = sumFemalegpa;


femaleCount++;


break;


case 'm':


studentGpa = sumMalegpa;


maleCount++;


break;





default:


cout %26lt;%26lt; "Invalid character" %26lt;%26lt; endl;


} //end switch statements





infile %26gt;%26gt; studentGender %26gt;%26gt; studentGpa;


} //end while statement





//Output results, cross fingers hope it works!!!


outfile %26lt;%26lt; "Sum female GPA = " %26lt;%26lt; sumFemalegpa %26lt;%26lt; endl;


outfile %26lt;%26lt; "Sum male GPA = " %26lt;%26lt; sumMalegpa %26lt;%26lt; endl;


outfile %26lt;%26lt; "Female count = " %26lt;%26lt; femaleCount %26lt;%26lt; endl;


outfile %26lt;%26lt; "Male count = " %26lt;%26lt; maleCount %26lt;%26lt; endl;


outfile %26lt;%26lt; "Average female GPA = " %26lt;%26lt; averageFemalegpa %26lt;%26lt; endl;


outfile %26lt;%26lt; "Average male GPA = " %26lt;%26lt; averageMalegpa %26lt;%26lt; endl;





system("pause");


return 0;


}

C++ program question?
Try closing outfile (and infile) before your program exits.





averageFemalegpa and averageMalegpa are also initialized to random values since the sums and counts aren't set to anything when you do the division.
Reply:try remove c:\\





Windows was finicky and worked when I did that...dunno why. maybe it's the same thing for you.





Shouldn't the average be calculated after a loop after you get a count?





It didn't make sence to me you were doing averages before the malecount++ and femalecount++


No comments:

Post a Comment