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?
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);
}
First of all, text_iois 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.
I just had a similar issue, so here's a simple mod file that will get take a simple string prompt and get a single line of input from the user. Please keep in mind that anything from a user could be hijacked by other processes so you need to run validations on what you got if this input will ever end up in a system with sensitive data.
Also if someone thinks this is useful enough to put on crates.io I'm fine with that, just mention me (Xpyder), and remove the .trim(). I'd do it myself but I haven't gotten that far in the Rust Book yet and I don't know it's use case is wide enough to warrant publishing anyways.
use simple_user_input::get_input;
fn main(){
let input: String = get_input("Please type something...");
println!("{}",input);
}
mod simple_user_input {
use std::io;
pub fn get_input(prompt: &str) -> String{
println!("{}",prompt);
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_goes_into_input_above) => {},
Err(_no_updates_is_fine) => {},
}
input.trim().to_string()
}
}
use std::io;
use std::io::*;
fn main(){
let mut input = String::new();
io::stdin::().read_line(&mut input).expect("error: unable to read user input");
println!("{}",input);
}