Rust for the Novice Programmer/Basic Maths Testing Program/User Input

Reading in User Input

edit

Now, we want to read in user input. In the terminal, when the user types in text it gets sent to something called stdin(short for standard input). Again we turn to the standard Rust documentation on stdin. Documentation is extremely important since very few programs live on their own, instead integrating with other code/systems to make it easier to do common things. stdin lies within std::io where std is short for standard and io is short for input/output. std is the Standard library which means it is officially designed and documented by the same group who design the Rust programming language. This generally offers a greater degree of certainty around the code being safe and performant as well as the documentation being clear and detailed. Here, we want to write a new function that waits for user input and when it receives that input, returns the number. First, let's just take in the input and print it out to the terminal:

fn wait_for_input() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    
    println!("{}", buffer);
}

Notably, the read_line() function takes in a mutable string rather than returning a string. This is because it can be costly to create and allocate a string of characters and if we want to append to an existing string, it would require an extra allocation. Therefore, taking in a string buffer allows the user to create their own string or use an existing string which is more flexible without extra cost. It also can fail and produce an error which is in the form of a Result. For now, we will just assume no error and panic if there is an error. Then, we remember to put

use std::io;

at the top, and change our main function to:

fn main() {
    print_question(35, 23, Operator::Subtraction);
    wait_for_input();
}

And now if we run it, we can see it doesn't stop immediately and we can type in the terminal. When we type something in and press Enter, the thing we typed in is repeated again, indicating that it's working! However, we have a string when we need the user input as a number.

Next: converting a string to a number