RustArena

Step 1 of 7

Reading a line with read_line

Until now your programs did the same thing every time they ran. Real programs react to input: what a user types, or data fed in from a file or another program. The simplest source is standard input, or stdin: the text typed into the terminal, or piped in with my_program < orders.txt. On this site, each test feeds your program its stdin; you'll see it in the Input box next to the expected output.

use std::io;

fn main() {
    println!("What's your name?");
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("failed to read a line");
    let name = name.trim();
    println!("Hello, {name}!");
}
Ferris
What's your name?
Hello, Ferris!

(The typed name isn't part of the program's output. In a terminal you'd see it because the terminal shows what you type, not because the program prints it.)

Line by line:

Seeing the newline

The debug format {:?} shows a string in quotes with special characters escaped, which makes the newline visible:

use std::io;

fn main() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("failed to read a line");
    println!("{:?}", line);
    println!("{:?}", line.trim());
    println!("{} bytes", line.len());
}
Ferris
"Ferris\n"
"Ferris"
7 bytes

On Windows, lines end with \r\n; trim() removes that too. Trimming input is a habit worth having everywhere.

Common mistakes

use std::io;

fn main() {
    let line = String::new();
    io::stdin().read_line(&mut line).expect("failed to read a line");
    println!("{line}");
}
error[E0596]: cannot borrow `line` as mutable, as it is not declared as mutable

Your task

Fill in the blanks so the program reads a city name and prints Welcome to <city>!.

Challenge 2

Fill the blanks to get the stdin handle and to lend line to read_line so it can write into it. The program prints the line in capital letters.

Challenge 3

Write the whole program: read a username, then print it (trimmed) and its length in characters:

user: ferris
length: 6

Some tests use names with accents, where bytes and characters differ.

Next: From text to numbers: parse