1

I am taking input number from user and then check if the number is positive, negative or zero. Positive number and zero checking performed but having problem in Negative number checking.

use std::io::Write;

fn main(){
    print!("Enter Number: ");
    let mut number = String::new();
    std::io::stdout().flush();
    std::io::stdin().read_line(&mut number);
    let num: u32 = number.trim().parse().unwrap();
}

when input is negative number, program becomes panic didn't parsing negative number.

0

1 Answer 1

7

When you replace u32 by i32 in the last line your program is able to handle negative numbers.

u32 means unsigned integer with 32bit width so parse() panics when it encounters a negative number. i32 is a signed integer so it works.

Not the answer you're looking for? Browse other questions tagged or ask your own question.