I’m struggling a bit to understand how to set this up properly.
Just a bit of background. I’m new to programming and I’ve only been using C++ for 3 weeks now.
We were given a problem to allow a user to enter any number of info using an EOF controlled while loop to iterate multiple entries.
While I’m able to set up the general code for this, I’m running into the issue of the last outputs of the loop still printing when I try to exit the loop using the eof function ctrl+z.
I set up the code to pre-read the data that’s input by the user before entering the loop, but when I initiate ctrl + z it exits the loop but still reads to the end of the loop and prints the output asking for data:
Enter the name of the destination: (ctrl+z here to exit loop using eof)
Enter the number of miles travelled: Enter the number of gallons used: (prints the rest of output)
How do I stop the last part from being output using ctrl + z?
Any help or input is appreciated
This is how I set up my initial code:
#include <iostream>
using namespace std;
//define variables
double milesTravelled, gallonUsed, mpg, total_miles, avg_mpgPerTrip;
int no_of_trips
string destiationName;
//set counters and sum to 0
no_of_trips = 0
total_miles = 0
//input phase
cout << "Enter the name of the destination";
cin >> destinationName;
cout << "Enter the number of miles travelled:"
cin >> milesTravelled
while(cin)
{
mpg = milesTravelled / gallonsUsed;
total_miles += milesTravelled;
no_of_trips ++;
cout << "Travel Information: n"
<< endl
<< "Destination: " << destinationName << endl
<< "Miles per Gallon: " << mpg << endl
<< endl;
cout << "Enter the name of the destination: ";
cin >> destinationName;
cout << "Enter the number of miles travelled: ";
cin >> milesTravelled;
cout << "Enter the number of gallons used: ";
cin >> gallonsUsed;
cout << endl;
}//end of loop
cout << endl
<< "Trip information entered: "
<< endl
<< "Total number of trips taken: " << no_of_trips << endl
<< "Total number of miles travelled: " << total_miles << endl;
}
I tried using a control structure using if, else to tell the program to exit based off of the EOF ctrl + z
Dasan Yang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.