Rust ParseIntError while asking input from users?

Viewed 360

I have a rust code in which it asks for the user input in a loop

use std::io;

fn main() {
    let mut string = String::new();

    loop {
        println!("Enter a value: ");
        let b = io::stdin().read_line(&mut string).expect("string");
        let val: u32 = string.trim().parse().expect("Error");

        println!("You typed: {:?}", val);
    }
}

This code works on the initial input but on inputting values the second time it panics and exists.

thread 'main' panicked at 'Error: ParseIntError { kind: InvalidDigit }', src/main.rs:13:20 note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

How do I solve this?

2 Answers

According to the rust docs std::io::stdin::read_line appends to the buffer so for the first iteration string contains for example 100, then on the second iteration string will contain 100\n100 and \n cannot be parsed as an int.

You can fix this by clearing string every iteration or simply

use std::io;

fn main() {
  loop {
    let mut string = String::new();
    println!("Enter a value: ");
    let b = io::stdin().read_line(&mut string).expect("string");
    let val: u32 = string.trim().parse().expect("Error");

    println!("You typed: {:?}", val);
  }
}

You're not resetting the string in your loop, so if you enter 10 on first go and 5 on second go, your string is actually "10\n5" and of course the new-line character isn't a valid digit.

EDIT: To add "How do I solve this" --> Take smaller steps. If the parsing fails, print out what you're trying to parse.

Related