Reputation: 3067
I have a for loop that asks the user for input using std::cin
then perform operations on it to obtain the distance between two longitude/latitude points. However, after the first iteration of the loop, std::cin
fails to execute and again using the variables stored on the first iteration of the loop.
#include<iostream>
#include<string>
#include<cmath>
#include<sstream>
#include<vector>
#include<iterator>
using namespace std;
int main()
{
string startingLocation;
int numDest;
string arrStart[3];
getline (cin, startingLocation);
stringstream ssinStart(startingLocation);
int k = 0;
string airport = "";
while (ssinStart.good() && k < 3)
{
if (k < 2)
{
ssinStart >> arrStart[k];
++k;
}
else
{
string mid;
ssinStart >> mid;
arrStart[k].append(mid);
arrStart[k].append(" ");
}
}
cin >> numDest;
string* destinations = new string[numDest];
double* distDest = new double[numDest];
string dest;
for (int i = 0; i < numDest; i++)
{
cin >> dest;
string arrDest[3];
stringstream ssinDest(dest);
int j = 0;
while(ssinDest.good() && j < 3)
{
if (j < 2)
{
ssinDest >> arrDest[j];
++j;
}
else
{
string mid;
ssinDest >> mid;
destinations[i].append(mid);
destinations[i].append(" ");
}
}
string delimiter = "/";
double lat1 = atof(arrStart[0].substr(0, arrStart[0].find(delimiter)).c_str());
double lat2 = atof(arrDest[0].substr(0, arrDest[0].find(delimiter)).c_str());
double lon1 = atof(arrStart[1].substr(0, arrStart[1].find(delimiter)).c_str());
double lon2 = atof(arrDest[1].substr(0, arrDest[1].find(delimiter)).c_str());
if (*arrStart[0].rbegin() == 'S')
{
lat1 = -lat1;
}
if (*arrDest[0].rbegin() == 'S')
{
lat2 = -lat2;
}
if (*arrStart[1].rbegin() == 'W')
{
lon1 = -lon1;
}
if (*arrDest[1].rbegin() == 'W')
{
lon2 = -lon2;
}
double dlat = lat1 - lat2;
double dlon = lon1 - lon2;
double R = 3959.9;
double a = pow(sin(dlat/2), 2) + cos(lat1) * cos(lat2) * pow(sin(dlon/2), 2);
double c = 2 * atan2(sqrt(a), sqrt(1-a));
double d = R * c;
distDest[i] = d;
}
for (int i = 0; i < numDest; i++)
{
cout << destinations[i] << ": " << distDest[i] << endl;
}
return 0;
}
The input takes the starting location, then the number of destinations (3 in this case), then should prompt the user to input 3 locations. However, after inputting the first location it iterates through the loop the remaining number of times then outputs the doubles at the end (that compounded onto each other). I'm assuming this is a memory issue since the variables defined inside the loop are being carried over between iterations, but I've had no luck searching on the issue.
I
159.123/N 145.22/W Los Angeles
3
124.22/N 23.1222/W San Francisco
O
: 10919
: 9065.76
: 7619.9
Upvotes: 0
Views: 148
Reputation: 5287
std::cin
only reads till whitespace. So when are you giving input 124.22/N 23.1222/W San Francisco, cin reads it as four strings. So you have given sufficient input for all the iterations. Use getline
method for reading complete line as you have used earlier.
Upvotes: 1