Display < retry > message inside loop for string input


I am quite new to rust, yet at the same time I'm itching to experiment with code.
I have studied the guessing game and I see that for each failed input the loop is performed again. I want to prevent this, and have the retry message triggered by the < Err(_) > method of the code.

fn reading() -> u32 {
println! ("insert number");
let mut a = String::new();
loop {
io::stdin() .read_line(&mut a) .expect("");
let a: u32 = match a.trim().parse(){
Ok(num) => num,
Err(_) => continue, // insert println! (retry message) here
break a;

Please read the pinned code formatting guide.

This function will loop forever in the face of IO errors, so the first change I suggest is:

-fn reading() -> u32 {
+fn reading() -> Result<u32, io::Error> {
     println!("insert number");
     let mut a = String::new();
     loop {
-        io::stdin().read_line(&mut a).expect("");
+        io::stdin().read_line(&mut a)?;
         let a: u32 = match a.trim().parse() {
             Ok(num) => num,
             Err(_) => continue, // insert println! (retry message) here
-        break a
+        break Ok(a);

The ? operator is covered later in the book; in short, if read_line returns an error, that error will be returned from the function.

Because we're returning a Result now, we have to wrap a in Ok when we return it.

To insert your message, you can just replace the single statement Err(_) match arm with a block instead:

-            Err(_) => continue, // insert println! (retry message) here
+            Err(e) => {
+                println!("I couldn't parse that ({e}); please try again");
+                continue
+            }

I'm including the error in the message ({e}).

Here's the code on the Playground.

There's actually still a bug in the program though, which has to do with how read_line works. You should see if you can figure out what's going on and how you could fix it.

1 Like

Hello & Thank you for the explanation. The information I was after was was the block you mentioned at the very end. I can see there is an error when running it; I think this error plagued my code when I tried trying something similar.

Your help is much appreciated!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.