parsing - 在 Rust 语言中将 String 解析为 Unsigned 的问题

标签 parsing rust

这是我的代码:

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/

相关文章:

javascript - 如何使用 Angular JS 将数据从 json 转换为对象列表

JavaScript:删除 HTML 标签、修改标签/文本以及将标签重新插入

c++ - boost::property_:tree - 解析和处理数据

haskell - 是否可以用 Rust 编写 Haskell 的翻转函数?

rust - 运行特定的.rs文件

syntax - “dyn”在类型中是什么意思?

arrays - Rust 中 array::len 的运行时复杂度是多少?

ios - NSXMLParser parse() 只工作一次

rust - 如何使我自己的适配器方法能够使用特征对象?

jquery - 如何使用没有外部名称的 .each 解析 json 数组?