How to check if a String is == to a particular String?

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.

I bet your string has a newline character at the end of it. Try printing your string with the {:?} formatter (rather than just with the {} formatter) to check.

1 Like

You forgot to trim temp_type. (Although you somehow remembered to trim value...)

Oh, you were right! I tested it and looked into how to remove /n, and it worked! Thank you

1 Like

Heh, that's because my understanding is limited and I grabbed a few things from when I did Chapter 2 of the book