我是一个新手,当它涉及到生 rust ,我一直得到这个错误,老实说,我不知道发生了什么事。我正在做一个华氏到摄氏度,反之亦然。这是我的代码:
use std::io;
fn main() {
let mut choose = String::new();
println!("Choose between Celsius To Fahrenheit [1] or Fahrenheit to Celsius [2],\
please introduce a corrected value (integer)");
io::stdin()
.read_line(&mut choose)
.expect("Failed to read!");
// Careful with the trim, cuz it's removing all characters and it causes and error that basically, closes the CMD
// Carriage return BE CAREFUL MAN!
if choose.trim() == "1" {
println!("Please, Introduce a value ");
io::stdin().read_line(&mut choose).expect("Please, enter an integer");
let choose: i32 = choose.trim().parse().expect("Jjaanokapasao");
ctof(choose);
} else if choose.trim() == "2" {
println!("Please, Introduce a value");
io::stdin().read_line(&mut choose).expect("Please, enter an integer");
let choose: usize = choose.trim_end().parse().expect("Failed to convert to i32");
ftpc(choose);
}
}
fn ctof(c: i32) {
let celsius_to_fahrenheit: i32 = (c * (9 / 5)) + 32;
println!("Here is your conversion: {celsius_to_fahrenheit}")
}
fn ftpc(f: usize) {
let fahrenheit_to_celsius: usize = (f-32) * (5 / 9);
println!("Here is your conversion: {fahrenheit_to_celsius}")
}
'''
1条答案
按热度按时间qybjjes11#
使用
.read_line()
读入String
将 append 到现有数据中,而不是 overwrite 它。它没有从字符串中删除。因此,如果您输入1
,然后输入26
,变量choose
将包含"1\n26\n"
。使用.trim()
将不会删除中间的换行符,因此.parse()
将遇到无效数字。您应该在再次写入
choose.clear()
之前调用它,否则请使用其他变量。