How to get user input?


#1

Hello, so, I’m new here, Rust seems cool and all, but I’m having a bit of a hard time to get user input from the console.

What’s the most easy, straightforward way to get user input from the console without the newline, and also without io:: and :: scattered around all the place, and with the less amout of lines possible?


#2

I would look at crates.io for a package: https://crates.io/crates/text_io is one example that comes to mind.


#3

Or using only std:

fn main() {
    use std::io::{stdin,stdout,Write};
    let mut s=String::new();
    print!("Please enter some text: ");
    let _=stdout().flush();
    stdin().read_line(&mut s).expect("Did not enter a correct string");
    if let Some('\n')=s.chars().next_back() {
        s.pop();
    }
    if let Some('\r')=s.chars().next_back() {
        s.pop();
    }
    println!("You typed: {}",s);
}

#4

First of all, text_io is pure Rust. Putting code in a crate doesn’t make it somehow less Rust. Secondly, your code doesn’t work correctly on Windows (which uses \r\n for newlines). Also, failure on read_line is unlikely to be the user’s fault. It’s not like they can type an entirely arbitrary line of text invalidly.

text_io probably is the absolute simplest way to do this, and I say that as someone with a horse in the race.


#5

They can input something that’s not UTF-8, which AFAICT is the only way read_line will not return Ok. Could be different on Windows.

Edited to address your other concerns.


#6

I’m trying to port some of my C++ code to Rust, and in C++ I just had to do:

string input;
getline(cin, input);
cout << input;


#7

Rust tries to be more correct, but also Rust standard library is rather young still, and some ergonomic concerns will need to be addressed.