I had to write a program to calculate average speed of a car during a trip and I have to prompt the user for the names of the two cities that they were traveling between. That program worked, but the next program we had to write is an addition to the last one, in which the user is prompted for how many times the program should run. I declared a new variable for the number of times the users needs the program to run. However when the program enters the loop it skips the first getline() method (asking for the origin city) and skips directly to the second getline() (method asking for the destination city). I have tried clearing the buffer and declaring the loop differently, but whatever I do the string is still read into the program as an empty string. Just wondering if I made a mistake on something or if I cannot use getline() in this instance.
Using C++ and Codeblocks IDE with the GNU Compiler (I've tried other compilers too)
Anyhow here is the code.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declare Variables
string orgcity = "";
string destcity = "";
int hours = 0;
double minutes = 0.0;
int hoursmin = 0;
int minutesmin = 0;
int minutesmax = 60;
double dist = 0.0;
double totalhours = 0.0;
double avespeed = 0.0;
double num1 = 0;
cout << "How many times would you like to calculate the average speed: ";
cin >> num1;
for(num1; num1 > 0; --num1)
{
//Collect Data
cout << "Enter the city of origin: ";
getline(cin, orgcity);
cout << "Enter the destination city: ";
getline(cin, destcity);
//If Statements and Loops...Start here
do {
cout << "Enter the number of hours spent in travel: ";
cin >> hours;
if (hours < hoursmin)
cout << " Invalid number of hours - must be >= 0" << endl;
} while (hours < hoursmin);
do {
cout << "Enter the number of minutes spent in travel: ";
cin >> minutes;
if (minutes >= minutesmax){
cout <<" Invalid number of minutes - must be in range 0..59" << endl;
}
if (minutes <= minutesmin) {
cout << " Invalid number of minutes - must be in range 0..59" << endl;
}
} while (minutes >= minutesmax);
//End Here
cout << "Enter the distance (in miles) between the two cities: ";
cin >> dist;
cout << endl;
//Formula and Final Prompt
totalhours = (hours + (minutes / 60.0));
avespeed = dist / totalhours;
cout << "The average speed of the vehicle traveling" << endl;
cout << "between " << orgcity << " and " << destcity << " is " << fixed << setprecision(2) << avespeed << " miles per hour." << endl;
cout << "-------------------------------------------------------------------------------" << endl;
}
return 0;
}