A simple CLI tool for converting between Celsius and Fahrenheit.
- Functions: Breaking logic into reusable pieces
- Input Validation: Ensuring users enter valid data
- Ownership Basics: Working with String types
- Control Flow: Loop-based program structure
- Type Conversion: Working with
f32for temperature calculations
- User enters a temperature value
- User selects scale (C or F)
- Program converts and displays result
- Option to convert another temperature
cargo runEnter temperature value
> 100
Scale?: (C for Celsius, F for Fahrenheit)
> C
You entered: C
Temperature: 100°C in Fahrenheit is 212°F
Do you want to convert another temperature? (y/n)
> n
fn read_temperature() -> f32 {
let temp: f32 = loop {
println!("Enter temperature value");
match get_input().parse::<f32>() {
Ok(num) => break num,
Err(_) => {
println!("Invalid input. Please enter a numeric value.");
continue;
}
};
};
temp
}fn convert(temp: f32, scale: &str) {
if scale == "C" {
let fahrenheit = (temp * 9.0 / 5.0) + 32.0;
println!("{}°C = {}°F", temp, fahrenheit);
} else {
let celsius = (temp - 32.0) * 5.0 / 9.0;
println!("{}°F = {}°C", temp, celsius);
}
}fn get_input() -> String {
let mut buf = String::new();
io::stdin().read_line(&mut buf).unwrap();
buf.trim().to_string()
}- Function Design: Creating focused, single-purpose functions
- String Ownership: Understanding when to use
&strvsString - Input Sanitization: Using
.trim()and.to_uppercase()for robust input - Error Recovery: Using loops to re-prompt on invalid input
- Float Arithmetic: Working with
f32for calculations
- Add Kelvin support
- Batch conversion from file
- Unit tests for conversion formulas
- Support for scientific notation input
- Add precision control (decimal places)
Status: ✅ Completed | Difficulty: Beginner