Issue with parsing String to Unsigned in Rust language

Viewed 68

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

1 Answers

You have a trailing \n in your string, use String::trim_end:

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

From 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.

Related