当我尝试从Read_line()解析输入时,我会得到Parseinterror {nick:invalidDigit}
我正在编写一个函数,该函数获得向量的初始长度,然后读取输入,直到填充向量为止。当我将输入字符串转换为整数时,事情出了问题。
fn read_to_vector(prompt: &str) -> Vec<String> {
println!("Enter the number of inital values: ");
let length_string:String = read_value();
let length = length_string.parse::<i32>().unwrap();
println!("{}", prompt);
let mut buffer_vector:Vec<String> = Vec::new();
for _i in 1..(length + 1) {
let buffer_str:String = read_value();
buffer_vector.push(buffer_str);
}
return buffer_vector;
}
fn read_value() -> String {
use std::io;
let mut buf:String = String::new();
io::stdin().read_line(&mut buf).expect("Failed to get input");
return buf;
}
这是错误消息:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src/main.rs:8:47
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
我在线搜索,但找不到任何相关的内容。
I am writing a function that gets an initial length of a vector then reads input until the vector is filled. Things go wrong when I convert the input string into an integer.
fn read_to_vector(prompt: &str) -> Vec<String> {
println!("Enter the number of inital values: ");
let length_string:String = read_value();
let length = length_string.parse::<i32>().unwrap();
println!("{}", prompt);
let mut buffer_vector:Vec<String> = Vec::new();
for _i in 1..(length + 1) {
let buffer_str:String = read_value();
buffer_vector.push(buffer_str);
}
return buffer_vector;
}
fn read_value() -> String {
use std::io;
let mut buf:String = String::new();
io::stdin().read_line(&mut buf).expect("Failed to get input");
return buf;
}
Here is the error message:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src/main.rs:8:47
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
I searched online but I could not find anything related.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
read_line()
不修剪任何空格。字符串末端可能有一个newline字符,这确实不是数字,这会导致解析失败。要解决此问题,请在返回字符串末端从字符串的末端修剪空格:要保存分配,您可以将
trim_end()
与truncate()
在拥有的字符串上:read_line()
does not trim any whitespace. There is probably a newline character at the end of the string, which indeed is not a digit, and this causes parsing to fail. To fix this, trim whitespace from the end of the string before returning it:To save an allocation, you can combine
trim_end()
withtruncate()
on the owned string: