Heyo!
I'm making a Celsius <-> Fahrenheit converter that works in the terminal, and working on the part that lets you input into the terminal. For some reason the string you input isn't detected by the if
block, even if it matches. Any insights?
use std::io;
fn main() {
loop {
println!("Please input the temperature.");
let mut temp_type = String::new();
let mut value = String::new();
io::stdin()
.read_line(&mut temp_type)
.expect("failed to read line");
io::stdin()
.read_line(&mut value)
.expect("failed to read line");
let value: i32 = match value.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
conversion(temp_type, value);
}
}
fn conversion(temp_type: String, mut temperature: i32) {
// Checks if it should convert to Fahrenheit
if temp_type == "f" {
temperature = (temperature * 9 + 162).div_euclid(5);
println!("Converted to Fahrenheit: {temperature}");
// Checks for Calsius
} else if temp_type == "c" {
temperature = (temperature * 5 - 156).div_euclid(9);
println!("Converted to Celsius: {temperature}");
} else {
println!("Please specify 'f' or 'c' in the first argument")
}
}
The full output:
Please input temperature
f # my input
30 # my second input
Please specify 'f' or 'c' in the first argument
Please input a temperature
# I can type here
Unless I'm mistaken, it's not registering that f
is the right string. I thought maybe it's because I'm incorrectly checking the String? I tried inputting + checking for char instead but I couldn't figure out how to do that lol.
Note: please excuse the probably messy code, I'm just trying to get it to work right now and am a novice.