Error when using read_line in a loop

⚓ Rust    📅 2026-02-13    👤 surdeus    👁️ 9      

surdeus

Warning

This post was published 52 days ago. The information described in this article may have changed.

This skeleton program gives an error (invalid digit) on the second pass through the loop, when the digit is correct.

use std::io;

fn main() {
	let mut inp = String::new();
	loop {
		println!("What do you want to do?");
		println!(" 1. Some option");
		println!(" 2. Another option");
		// ...... further options
		println!(" 0. Exit");

		io::stdin()
			.read_line(&mut inp)
			.expect("Failed to read line");
		let choice: u32 = inp.trim().parse().expect("Not a number!");
		if choice == 0 { println!("Goodbye!"); break }
	}
}

5 posts - 4 participants

Read full topic

🏷️ Rust_feed