1

I am making a program that asks a user's age:

use std::io;

fn main() {
    println!("How Old Are You?");

    let mut age = String::new();
    io::stdin().read_line(&mut age).expect("Failed to get age");

    println!("You are {} years old!", age);
}

Once the user enters their age (8 for example) read_line inserts a '\n' to what the user inputs. The result looks like

You are 8  
 years old!

I know I can use something like this to remove the '\n' before displaying the age:

let age = age.trim();  

Is there an alternative I could use to read user input simply that won't add anything to the variable.

Melon Bread
  • 321
  • 1
  • 2
  • 10
  • 5
    `read_line` doesn't "add" anything to the input; the user *typed* the Enter key. – Shepmaster Mar 24 '18 at 14:11
  • Please [edit] your question to explain why it isn't already answered by [How to read an integer input from the user in Rust 1.0?](https://stackoverflow.com/q/30355185/155423), specifically by [this answer using text_io](https://stackoverflow.com/a/30355516/155423). – Shepmaster Mar 24 '18 at 14:13
  • @Shepmaster Oh that makes so much sense! Thanks, I never thought about it like that. – Melon Bread Mar 24 '18 at 14:27
  • @Shepmaster this answered my question – Melon Bread Mar 24 '18 at 14:37

0 Answers0