my program is supposed to use a .txt file as input (time in seconds 1 through 10) to calculate the distance of a falling object. The text file reads as follows:
1
2
3
4
5
6
7
8
9
10
And here is my code so far.
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;
//function prototype
double fallingDistance (int);
void main()
{
ifstream inputFile;
int time;
double distance;
//open the file
inputFile.open("05.txt");
inputFile >> time;
{
distance = fallingDistance (time);
cout << time << "\t\t" << distance << endl;
}
}
double fallingDistance (int time)
{
double distance, gravity=9.8;
distance = static_cast<double>(0.5 * gravity * pow(time,2));
return distance;
}
And this is what my program compiles:
1 4.9
press any key to continue...
Thanks in advance!
You first read an
intfrom the input file. Next you initializedistanceusingtime. Then you’re printing the value oftime, two tabs, and lastly, the value ofdistance.After this line executes
mainreturns and your program exits. Why would you expect it to print anything else?If you need to grab more values from the file then you need to use a loop, wrapping that entire process in a loop which reads from the file until it gets through the whole thing. Something like:
On a side note,
mainis defined by the standard to have a return type ofint, notvoid. Omitting the arguments (int argcandchar *argv[]) as you have done is fine.