Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust taking input in the same variable more than once behavior. Can anyone explain?

So I tried to take input into the same variable called input with a loop. It behaves in a way that I do not know why.
Here is the snippet

use std::io::stdin;

fn main(){
    println!("Please Give Input: ");
    let mut input = String::new();
    loop{
        stdin().read_line(&mut input).expect("Error While Input");
        print!("{input}");
    }
}

on the first input it just prints the result. For Example: if I input 1, it outputs 1. but on the second input if I input A it is going to output: 1 A and it goes on.

Thank you in Advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am trying to learn coding in rust. I was just experimenting with taking valid input from the command-line by looping through it multiple times, until the user inputs something valid. I was expecting only 1 value to stay in the variable but it has multiple values See Image

>Solution :

https://doc.rust-lang.org/std/io/struct.Stdin.html#method.read_line

readline appends to the buffer. Move your String::new into the loop if you want just the last input

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading