coding-horror/basic-computer-games · error

Failed to get Input

Error message

Failed to get Input

What it means

In 33_Dice, the readinput helper prints a labeled prompt, flushes stdout, then reads input via io::stdin().read_line(...).expect("Failed to get Input"). All player input in the Dice game flows through this function. The panic triggers when stdin returns Err (EOF, broken pipe, invalid fd). Note: the preceding io::stdout().flush().unwrap() has the same fragility but is not the subject of this error.

Source

Thrown at 33_Dice/rust/src/main.rs:83

        // Continue the game
        let reply = readinput("TRY AGAIN").to_ascii_uppercase();
        if reply.starts_with("Y") || reply.eq("YES") {
            frequency = [0; 13];
        } else {
            playing = false;
        }
    }
}

// function for getting input on same line
fn readinput(str: &str) -> String {
    print!("\n{}? ", str);
    let mut input = String::new();
    io::stdout().flush().unwrap();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to get Input");
    input
}

View on GitHub (pinned to 5301155192)

Solutions

  1. Change readinput to return Option<String> and have callers handle None by exiting or using a default
  2. Replace .expect() with .unwrap_or_default() so an I/O failure yields an empty string that callers can treat as invalid input
  3. Return Result<String, io::Error> and use ? in callers

Example fix

// before
fn readinput(str: &str) -> String {
    print!("\n{}? ", str);
    let mut input = String::new();
    io::stdout().flush().unwrap();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to get Input");
    input
}

// after
fn readinput(str: &str) -> Option<String> {
    print!("\n{}? ", str);
    let _ = io::stdout().flush();
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(0) | Err(_) => None,
        Ok(_) => Some(input),
    }
}
Defensive patterns

Strategy: fallback

Try / catch

fn readinput(str: &str) -> Option<String> {
    print!("\n{}? ", str);
    let _ = io::stdout().flush();
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(0) | Err(_) => None,
        Ok(_) => Some(input),
    }
}

Prevention

When it happens

Trigger: Any input prompt in the Dice game when stdin is at EOF or the read fails. Since readinput is the sole input function, exhausting piped input at any point crashes the game.

Common situations: Running the Dice game with scripted input that runs out, pressing Ctrl+D during a bet or roll prompt, or CI testing without sufficient input lines.

Related errors


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