coding-horror/basic-computer-games · error

Error reading from stdin

Error message

Error reading from stdin

What it means

In 25_Chief, check_yes_answer reads a yes/no response via io::stdin().read_line(&mut answer).expect("Error reading from stdin"). The .expect() panics if read_line returns Err, which occurs when stdin reaches EOF (input stream closed) or the stdin file descriptor is invalid. The function is called to check whether the user's answer starts with 'Y' across multiple points in the game's dialogue.

Source

Thrown at 25_Chief/rust/src/main.rs:53

              X X
             X X
            XX
           X
          *

#########################

I HOPE YOU BELIEVE ME NOW, FOR YOUR SAKE!!"
    );
}

fn check_yes_answer() -> bool {
    // reads from input and return true if it starts with Y or y

    let mut answer: String = String::new();
    io::stdin()
        .read_line(&mut answer)
        .expect("Error reading from stdin");

    answer.to_uppercase().starts_with('Y')
}

fn main() {
    const PAGE_WIDTH: usize = 64;
    print_center("CHIEF".to_string(), PAGE_WIDTH);
    print_center(
        "CREATIVE COMPUTING  MORRISTOWN, NEW JERSEY".to_string(),
        PAGE_WIDTH,
    );
    println!("\n\n\n");

    println!("I AM CHIEF NUMBERS FREEK, THE GREAT INDIAN MATH GOD.");
    println!("ARE YOU READY TO TAKE THE TEST YOU CALLED ME OUT FOR?");

    if !check_yes_answer() {
        println!("SHUT UP, PALE FACE WITH WISE TONGUE.");

View on GitHub (pinned to 5301155192)

Solutions

  1. Replace .expect() with a match that returns false on Err, treating an I/O failure as a 'no' answer
  2. Check whether read_line returned 0 bytes (EOF) and exit the game gracefully with a farewell message
  3. Wrap the read in a helper that returns Option<String> and have callers decide how to handle None

Example fix

// before
io::stdin()
    .read_line(&mut answer)
    .expect("Error reading from stdin");

// after
if io::stdin().read_line(&mut answer).is_err() {
    return false;
}
Defensive patterns

Strategy: try-catch

Try / catch

match io::stdin().read_line(&mut answer) {
    Ok(0) => return false,  // EOF
    Ok(_) => { /* process answer */ }
    Err(_) => return false,
}

Prevention

When it happens

Trigger: Piping fewer input lines than the game expects (printf 'Y\n' | cargo run when check_yes_answer is called twice), pressing Ctrl+D at the terminal to send EOF, or running in a non-interactive shell where stdin is /dev/null or closed.

Common situations: Automated test scripts that provide insufficient input, running the game in CI without allocating a PTY, piping from a here-doc with too few lines, or a user closing the terminal window mid-game.

Related errors


AI-assisted analysis of coding-horror/basic-computer-games@5301155192 (2026-08-13). Data as JSON: /api/errors/f0af008e69cb8bf8. Report an issue: GitHub.