Modifying a program to take input data.

I have been tinkering around with this problem for the better part of an hour and after having looked everywhere I'm not sure what to do.
Any help would be greatly appreciated.

I have to take this problem(which I've already coded)
and modify it to take input data from a file.

5) A liter is 0.264179 gallons. Write a program that will read in the number of liters of gasoline consumed by the user’s car and the number of miles traveled by the car. Then, output the number of miles per gallon the car delivered. Your program should allow the user to repeat this calculation as often as the user wishes. Define a function to compute the number of miles per gallon. Your program should use a globally defined constant for the number of liters per gallon.

7) Modify your program from number 5 so that it will take input data, from a file called “data.dat”.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Problem 5:

double mPG (double liters, double milesTraveled)
{
    double gallon = liters * 0.264179;
    return milesTraveled / gallon;
}
 
int main(int argc, char** argv) {

    string userInput;
    double milesTraveled, litersUsed;
    do{
        cout << "Enter the number of miles you traveled and the number of"
                " liters you vehicle used to calculate your MPG.\n";
        cout << "Number of miles traveled: ";
        cin >> milesTraveled;
        cout << "Number of liters used: ";
        cin >> litersUsed;
        cout << "Your vehicle gets " << mPG(litersUsed, milesTraveled) <<
                " miles to the gallon.\n";
        
    cout << "Would you like to calculate the MPG for another vehicle?"
            "Enter Y for yes or any or other key for no: ";
    cin >> userInput;
    }while(userInput == "Y");
    
    return 0;


And I know I messed up number 7 really bad trying to figure this out.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
double mPG (double liters, double milesTraveled)
{
    double gallon = liters * 0.264179;
    return milesTraveled / gallon;
}
 
int main(int argc, char** argv) {

    ofstream outfile;
    outfile.open("data.txt");
    outfile << "1000 20 liters used.\n";
    outfile.close();
    ifstream infile;
    infile.open("data.txt");
    double input;
    double read = infile >> input;
    
    double milesTraveled, litersUsed;
    cout << "Enter the number of miles you traveled and the number of"
            " liters you vehicle used to calculate your MPG.\n";
    cout << "Your vehicle gets " << mPG(read, read) <<
            " miles to the gallon.\n";
    infile.close();
    return 0;
Shouldn't your input file contain the answers the user gave when you ran problem five? Try approaching it from that angle.
Topic archived. No new replies allowed.