> C++ Can't get this code to work?

C++ Can't get this code to work?

Posted at: 2014-12-18 
When redirecting your information to the file, you should use

out_s << "\t x \t\t x^2 \t\t Current Sum \n";

well i tried to compile your code it works, made an input.txt to read numbers, but i notice that your output.txt is empty. It seems that you didn't output your results/numbers into your output file. Is that your problem or is it some other error?

The code is suppose to read the file input.txt and display display the results. It is then suppose to output it to a file called output.txt . I can't figure out what I did wrong.

#include

#include // Step (1)

#include

#include

using namespace std;

int main( )

{

double x;

int count = 0;

float sum = 0, avg;

char input_file[15]; // Step (2)-A

ifstream in_s; // Step (2)-B - declaration of the stream of type input

ofstream out_s;

cout << "Please input the input file name \n"; // Step (3)-A Get the file name

cin >> input_file;

in_s.open(input_file); // Step (3)-B - connect to the input file and test

out_s.open("output.txt");

if(in_s.fail( ))

{

cout << "Input file opening failed. \n";

exit(1); // if we couldn't open the file to read from we exit

}

if(out_s.fail( ))

{

cout << "Input file opening failed. \n";

exit(1); // if we couldn't open the file to read from we exit

}

cout << "\t x \t\t x^2 \t\t Current Sum \n";

cout << "\t === \t\t === \t\t ========== \n";

while( in_s >> x) // Step (4)-Read all numbers one-by-one to the end of the file

{

sum = sum + x;

cout << "\t " << x <<"\t\t " << pow(x,2) << "\t\t " << sum << "\n";

count++;

}

avg = sum/count;

cout << "\n \t\t The average of these " << count << " numbers is: " << avg

<< endl;

in_s.close( ); // Step (5)-Close the connection (close the file)

out_s.close( );

return 0;

}