How do I rewrite the following code such that each output has it’s own prompt (see desired outcome) – g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::string;
int main() {
cout << "Enter a numeric value followed by a unit abbreviation (km,mi): ";
double initial_value;
string initial_unit;
cin >> initial_value >> initial_unit;
double conversion_factor = {initial_value *1.609};
double conversion_factor2 = {initial_value /1.609};
std::string miles = "mi";
std::string kilometers = "km";
if (initial_unit == miles) {
cout << initial_value << " " << initial_unit << " "<< "is" << " " << conversion_factor << "n" << "km";
}
if (initial_unit == kilometers) {
cout << initial_value << " " << initial_unit << " "<< "is" << " " << conversion_factor2 << "n" << "mi";
}
else (initial_unit != kilometers, miles);
{
cout << "Unknown unit, please try again";
}
return 0;
}
Outcome I am getting:
Enter a numeric value followed by a unit abbreviation (km,mi): 10 mi
10 mi is 16.09
kmUnknown unit, please try again
Example of desired outcome:
Enter a numeric value followed by a unit abbreviation (km,mi):
10 mi
10 mi is 16.09 km
16.09 km
16.09 km is 10 mi
20000 leagues
Unknown unit, please try again
0.5 mi
0.5 mi is 0.8045 km
2
Answers
You have gotten quite mixed up. The following code has multiple problems.
Let’s break that up to show what’s actually happening:
The correct chain of conditionals is:
The statement
else (initial_unit != kilometers, miles);
is completely wrong.For one thing, the
;
should not be there. That is causing your code to output theUnknown unit
message regardless of whatinitial_unit
is actually set to.But more importantly, you can’t compare a single value against a comma-separated list of values like you are trying to do. Due to the comma operator and operator precedence, the expression
initial_unit != kilometers, miles
would be interpreted as(initial_unit != kilometers), miles
and thus the result of the expression would bemiles
regardless of whatinitial_unit
is actually set to.You have to compare each value individually, like this:
But, you already compared
initial_unit
againstkilometers
andmiles
before that statement, so there is no need to compare them again. The statement should be just anelse
by itself, eg:Now, that being said, to do what you are asking, you need to run a loop, where each iteration prompts the user for new input, eg: