Benjamin Helfman
asked on
help with cin << string
I am attempting to run a while loop:
int main() {
double measurement=0;
string unit_of_measurement = " ";
//conversion factors
double meterToCentimeter = 100;
double inchToCentimeter = 2.54;
double footToInches = 12;
double centimeters=0.0;
//define two variables to keep track of which is smallest and largest so far
double smallestSoFar=0.0, largestSoFar=0.0;
cout<<"Enter a float and then hit enter.\n";
vector<double> Values;
unsigned int size_of_values = 0;
while (cin >> measurement >> unit_of_measurement) { // *** Crashes here when ft or in ***
//convert measurement to centimeters
if (unit_of_measurement == "m") centimeters = measurement*meterToCentimeter;
if (unit_of_measurement == "in") centimeters = measurement*inchToCentimeter;
if (unit_of_measurement == "ft") centimeters = (measurement*footToInches)*inchToCentimeter;
//Add measurement to the vector
Values.push_back(measurement);
//Assign the size of the vector to size_of_values
size_of_values = Values.size();
//Using ranged based for loop
for (double i : Values) {
//if this is the first time around the while loop then the first value is both largest and smallest
if (size_of_values==1) {
cout << "The largest and smallest so far is " << measurement << unit_of_measurement << "\n";
largestSoFar = centimeters;
smallestSoFar = centimeters;
// else determine if measurement is greater than largestSoFar or smaller than smallestSoFar (which were assigned the first time through the loop
} else {
if (centimeters > largestSoFar) {
largestSoFar = centimeters;
}
if (centimeters < smallestSoFar) {
smallestSoFar = centimeters;
}
}
}
cout << largestSoFar << "cm " << " is the largest so far \n" << smallestSoFar << "cm " << " is the smallest so far: \n";
cout << "End of Outside For Loop\n\n";
} // end of for loop
return 0;
}
When I enter a double and "m" (bolded above), the program works as I expect. When I try to use "in" or "ft", the program execution exits the loop and terminates.
Your cin is parsing based on whitespaces.
If your first entry is not an integer or a double, then the parsing fails.
One way to handle the case of 14.3in is to read those 6 chars into a string, and then parse it yourself.
If your first entry is not an integer or a double, then the parsing fails.
One way to handle the case of 14.3in is to read those 6 chars into a string, and then parse it yourself.
ASKER
Why does 14m work fine then?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER