0
0
Rustprogramming~20 mins

Reading input basics in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust Input Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this Rust code reading input?

Consider this Rust program that reads a line from the user and prints it back:

use std::io::{self, Write};

fn main() {
    let mut input = String::new();
    print!("Enter your name: ");
    io::stdout().flush().unwrap();
    io::stdin().read_line(&mut input).unwrap();
    println!("Hello, {}!", input.trim());
}

If the user types Alex and presses Enter, what will be printed?

Rust
use std::io::{self, Write};

fn main() {
    let mut input = String::new();
    print!("Enter your name: ");
    io::stdout().flush().unwrap();
    io::stdin().read_line(&mut input).unwrap();
    println!("Hello, {}!", input.trim());
}
AEnter your name: Hello, Alex!
BHello, Alex!\n
CHello, Alex!\nEnter your name:
DEnter your name: Hello, Alex!\n
Attempts:
2 left
๐Ÿ’ก Hint

Remember that print! does not add a newline, so the prompt stays on the same line.

โ“ Predict Output
intermediate
2:00remaining
What error occurs when reading input without mutable String?

Look at this Rust code snippet:

use std::io;

fn main() {
    let input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    println!("You typed: {}", input);
}

What error will the compiler produce?

Rust
use std::io;

fn main() {
    let input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    println!("You typed: {}", input);
}
Aerror: missing semicolon after `String::new()`
Berror: cannot borrow immutable local variable `input` as mutable
Cerror: expected `&mut String` but found `&String`
Derror: cannot move out of borrowed content
Attempts:
2 left
๐Ÿ’ก Hint

Think about whether the variable can be changed when passed as mutable reference.

โ“ Predict Output
advanced
2:00remaining
What is the output of this Rust code reading multiple inputs?

Consider this Rust program:

use std::io;

fn main() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    let numbers: Vec = buffer
        .trim()
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    println!("Sum: {}", numbers.iter().sum::());
}

If the user inputs 10 20 30 and presses Enter, what will be printed?

Rust
use std::io;

fn main() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    let numbers: Vec<i32> = buffer
        .trim()
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    println!("Sum: {}", numbers.iter().sum::<i32>());
}
ASum: 60
BSum: 10 20 30
CSum: 0
DSum: 102030
Attempts:
2 left
๐Ÿ’ก Hint

Think about how the input string is split and parsed into numbers before summing.

โ“ Predict Output
advanced
2:00remaining
What error occurs when parsing invalid input to integer?

Look at this Rust code:

use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let num: i32 = input.trim().parse().unwrap();
    println!("Number is {}", num);
}

If the user types abc and presses Enter, what happens?

Rust
use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let num: i32 = input.trim().parse().unwrap();
    println!("Number is {}", num);
}
AProgram panics with a parse error
BProgram prints: Number is 0
CProgram waits for more input
DProgram prints: Number is abc
Attempts:
2 left
๐Ÿ’ก Hint

What happens if you try to convert a non-number string to an integer?

๐Ÿง  Conceptual
expert
3:00remaining
How to correctly read multiple lines of input until EOF in Rust?

You want to read multiple lines from standard input until there is no more input (EOF). Which Rust code snippet correctly does this?

A
use std::io;

fn main() {
    let mut input = String::new();
    while io::stdin().read_line(&amp;mut input).unwrap() != 0 {
        println!("Read: {}", input);
        input.clear();
    }
}
B
use std::io;

fn main() {
    let mut input = String::new();
    while io::stdin().read_line(&amp;mut input).unwrap() &gt; 0 {
        println!("Read: {}", input.trim());
        input.clear();
    }
}
C
use std::io::{self, BufRead};

fn main() {
    for line in io::stdin().lock().lines() {
        let line = line.unwrap();
        println!("Read: {}", line);
    }
}
D
use std::io;

fn main() {
    loop {
        let mut input = String::new();
        io::stdin().read_line(&amp;mut input).unwrap();
        if input.is_empty() { break; }
        println!("Read: {}", input.trim());
    }
}
Attempts:
2 left
๐Ÿ’ก Hint

Think about how to handle input lines safely and efficiently until EOF.