Bird
Raised Fist0
Rustprogramming~20 mins

Handling input values in Rust - Practice Problems & Coding Challenges

Choose your learning style10 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 standard input 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!\nEnter your name:
CEnter your name: Hello, Alex\n!
DHello, Alex!
Attempts:
2 left
๐Ÿ’ก Hint

Remember that print! does not add a newline, so flushing is needed to show the prompt before input.

โ“ Predict Output
intermediate
2:00remaining
What error does this Rust code produce when reading input?

Look at this Rust code snippet:

use std::io;

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

What error will this code cause when compiled?

Rust
use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(input).unwrap();
    println!("You typed: {}", input);
}
Aerror[E0599]: no method named `read_line` found for struct `String`
Berror[E0308]: mismatched types: expected &mut String, found struct String
CNo error, runs correctly
Derror[E0425]: cannot find value `input` in this scope
Attempts:
2 left
๐Ÿ’ก Hint

Check the argument type expected by read_line.

๐Ÿ”ง Debug
advanced
2:00remaining
Why does this Rust program panic when parsing input?

Examine 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 plus 10 is {}", num + 10);
}

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 plus 10 is {}", num + 10);
}
AProgram panics with a parse error at unwrap()
BProgram prints: Number plus 10 is 10
CProgram prints: Number plus 10 is abc10
DProgram waits for more input indefinitely
Attempts:
2 left
๐Ÿ’ก Hint

What happens if parse() fails and you call unwrap()?

๐Ÿ“ Syntax
advanced
2:00remaining
Which Rust code correctly reads and parses an integer input?

Choose the Rust code snippet that correctly reads a line from input and parses it as an i32 without panicking.

A
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let num: i32 = input.parse().unwrap();
B
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let num: i32 = input.trim().parse().unwrap();
C
let mut input = String::new();
io::stdin().read_line(input).unwrap();
let num: i32 = input.trim().parse().unwrap();
D
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let num: i32 = match input.trim().parse() {
    Ok(n) => n,
    Err(_) => 0,
};
Attempts:
2 left
๐Ÿ’ก Hint

Look for safe parsing that handles errors.

๐Ÿš€ Application
expert
3:00remaining
How many items are in the vector after this input processing?

This Rust program reads a line of space-separated numbers and collects them into a vector:

use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let numbers: Vec = input
        .trim()
        .split(' ')
        .filter_map(|s| s.parse().ok())
        .collect();
    println!("Count: {}", numbers.len());
}

If the user inputs: 10 20 abc 30 40x 50 and presses Enter, what will be printed?

Rust
use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let numbers: Vec<i32> = input
        .trim()
        .split(' ')
        .filter_map(|s| s.parse().ok())
        .collect();
    println!("Count: {}", numbers.len());
}
ACount: 5
BCount: 3
CCount: 4
DCount: 6
Attempts:
2 left
๐Ÿ’ก Hint

Only valid integers are collected. Non-integers are skipped.

Practice

(1/5)
1. What does the Rust function io::stdin().read_line(&mut input) do in a program?
easy
A. It clears the input buffer.
B. It writes a line of text to the screen.
C. It reads a line of text from the user and stores it in the variable input.
D. It converts a string to a number.

Solution

  1. Step 1: Understand the function purpose

    io::stdin().read_line(&mut input) reads user input from the keyboard as a string.
  2. Step 2: Recognize the role of input

    The input is stored in the mutable variable input passed by reference.
  3. Final Answer:

    It reads a line of text from the user and stores it in the variable input. -> Option C
  4. Quick Check:

    read_line reads user input [OK]
Hint: read_line reads user input into a variable [OK]
Common Mistakes:
  • Thinking read_line writes output
  • Confusing input reading with clearing buffer
  • Assuming it converts types automatically
2. Which of the following Rust code snippets correctly reads a line of input and trims whitespace?
easy
A. let input = io::stdin().read_line().trim();
B. let mut input = String::new(); io::stdin().read_line(&mut input).expect("Failed"); let input = input.trim();
C. io::stdin().read_line(input); let input = input.trim();
D. let mut input = String::new(); io::stdin().read_line(input); input.trim();

Solution

  1. Step 1: Check correct usage of read_line

    It requires a mutable String reference: read_line(&mut input).
  2. Step 2: Confirm trimming is done on the input string

    Calling input.trim() removes whitespace correctly.
  3. Final Answer:

    let mut input = String::new(); io::stdin().read_line(&mut input).expect("Failed"); let input = input.trim(); -> Option B
  4. Quick Check:

    read_line needs &mut String and trim() cleans input [OK]
Hint: Use &mut String and call trim() after read_line [OK]
Common Mistakes:
  • Forgetting &mut before input
  • Calling trim() on read_line() result
  • Not creating a mutable String first
3. What will be the output of this Rust code if the user inputs 42?
use std::io;
fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed");
    let num: i32 = input.trim().parse().expect("Not a number");
    println!("Number plus 10 is {}", num + 10);
}
medium
A. Number plus 10 is 52
B. Number plus 10 is 42
C. Not a number
D. Failed

Solution

  1. Step 1: Read and parse input

    The input string "42" is trimmed and parsed to integer 42 successfully.
  2. Step 2: Add 10 and print

    42 + 10 equals 52, so the output prints "Number plus 10 is 52".
  3. Final Answer:

    Number plus 10 is 52 -> Option A
  4. Quick Check:

    42 + 10 = 52 [OK]
Hint: Trim and parse input before math operations [OK]
Common Mistakes:
  • Not trimming input before parse
  • Parsing input as wrong type
  • Ignoring parse errors
4. Identify the error in this Rust code snippet that reads an integer from input:
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed");
let num: i32 = input.parse().expect("Not a number");
println!("Number: {}", num);
medium
A. parse() called without trimming input
B. Missing &mut before input in read_line
C. input is not mutable
D. println! macro syntax error

Solution

  1. Step 1: Check read_line usage

    read_line correctly uses &mut input and input is mutable.
  2. Step 2: Identify parse error cause

    parse() is called on input without trimming, so newline remains causing parse failure.
  3. Final Answer:

    parse() called without trimming input -> Option A
  4. Quick Check:

    Always trim input before parse() [OK]
Hint: Always trim input string before parsing to number [OK]
Common Mistakes:
  • Forgetting to trim input before parse
  • Assuming read_line returns trimmed string
  • Misusing &mut in read_line
5. You want to read multiple numbers from user input separated by spaces and store them in a vector of integers. Which Rust code correctly does this?
use std::io;
fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed");
    let numbers: Vec<i32> = input.trim().split_whitespace()
        .map(|x| x.parse().expect("Not a number"))
        .collect();
    println!("Numbers: {:?}", numbers);
}
hard
A. read_line() cannot read multiple numbers at once.
B. Fails because split_whitespace() does not split strings.
C. parse() should be called before split_whitespace().
D. Correctly reads and parses space-separated numbers into a vector.

Solution

  1. Step 1: Read input line and trim

    Input is read as a string and trimmed to remove trailing whitespace.
  2. Step 2: Split and parse each number

    split_whitespace() splits input by spaces, map parses each piece to i32, collect gathers into vector.
  3. Final Answer:

    Correctly reads and parses space-separated numbers into a vector. -> Option D
  4. Quick Check:

    split_whitespace + map(parse) + collect = vector [OK]
Hint: Use split_whitespace, map parse, then collect to vector [OK]
Common Mistakes:
  • Parsing before splitting input
  • Using wrong iterator methods
  • Assuming read_line reads multiple inputs separately
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard