简体   繁体   English

在 Rust 语言中将字符串解析为无符号的问题

[英]Issue with parsing String to Unsigned in Rust language

This is the code I have:这是我的代码:

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);
}

I get no error while compiling, but it prints this in running time:编译时没有错误,但它会在运行时打印:

Err(ParseIntError { kind: InvalidDigit })

You have a trailing \n in your string, use String::trim_end :您的字符串中有一个尾随\n ,请使用String::trim_end

fn main() {
  let n = "10\n".trim_end().parse::<u32>();
  println!("Try: {:?}", n);
}

From BufRead::read_line documentation :来自BufRead::read_line 文档

This function will read bytes from the underlying stream until the newline delimiter (the 0xA byte) or EOF is found.此 function 将从底层 stream 读取字节,直到找到换行符分隔符(0xA 字节)或 EOF。 Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf.一旦找到,所有字节(包括分隔符)(如果找到)都将附加到 buf。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM