这是我的代码:
fn main() {
use std::io::stdin;
let mut s=String::new();
stdin().read_line(&mut s).expect("Wrong input");
let n = s.parse::<u32>();
println!("Try: {:?}", n);
}
我在编译时没有出错,但它在运行时打印了这个:
Err(ParseIntError { kind: InvalidDigit })
最佳答案
您的字符串中有尾随 \n
,请使用 String::trim_end
:
fn main() {
let n = "10\n".trim_end().parse::<u32>();
println!("Try: {:?}", n);
}
来自 BufRead::read_line
documentation :
This function will read bytes from the underlying stream until the newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf.
关于parsing - 在 Rust 语言中将 String 解析为 Unsigned 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67535784/