Char To Digit Input Validation

Parse user keystrokes with char::to_digit so each character is validated in radix before any arithmetic happens.

RustForm Validation

Code

rustsnippet
24 lines
// 逐字符 to_digit(radix):非该进制字符返回 None
fn parse_digits(input: &str) -> Option<Vec<u32>> {
    input.chars().map(|c| c.to_digit(10)).collect()
}

fn sum_digits(input: &str) -> u32 {
    parse_digits(input)
        .map(|digits| digits.iter().sum())
        .unwrap_or(0)
}

fn main() {
    let attempts = ["2048", "20x8", "ff", ""];
    for attempt in attempts {
        match parse_digits(attempt) {
            Some(digits) => println!("{attempt:?} -> {digits:?} sum {}", sum_digits(attempt)),
            None => println!("{attempt:?} -> rejected"),
        }
    }

    // 十六进制:to_digit(16) 接受 a-f 与 A-F
    let hex: Vec<u32> = "DeAdBeEf".chars().map(|c| c.to_digit(16).unwrap()).collect();
    println!("hex digits: {hex:?}");
}

How it works

Char To Digit Input Validation comes down to the functions parse_digits, sum_digits and main.

A single loop drives the file — for attempt in attempts. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: fn parse_digits(input: &str) -> Option<Vec<u32>>

Running the file prints labeled results such as hex digits: — each operation’s effect is visible in the output.

Running the file executes main, which drives parse_digits and sum_digits in order.

Key statements

let hex: Vec<u32> = "DeAdBeEf".chars().map(|c| c.to_digit(16).unwrap()).collect();
.map(|digits| digits.iter().sum())
.unwrap_or(0)
}
input.chars().map(|c| c.to_digit(10)).collect()
}

Interactive Tools for This Topic

FAQ

What does Char To Digit Input Validation print when run?
Running the file directly is enough — expect labeled output lines such as `hex digits:`.