Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When I read the number by read_byte, it prints I guess ASCII number.. #3479

Closed
ghost opened this issue Sep 13, 2012 · 1 comment
Closed

When I read the number by read_byte, it prints I guess ASCII number.. #3479

ghost opened this issue Sep 13, 2012 · 1 comment

Comments

@ghost
Copy link

ghost commented Sep 13, 2012

How can I read pure decimal?

Please Let me know it .

I attach source below.

fn main(){
    let my_number = io::stdin().read_byte() as int;
//    let mut my_number = 0;
    io::println(int::str(my_number));    

    match my_number{
        0       =>  io::println("zero"),
        1|2     =>  io::println("one or two"),
        3..10   =>  io::println("three to ten"),
        _       =>  io::println("something else")
    }   

}

OUTPUT
1
49
something else

@AngryLawyer
Copy link

Read byte only gets you a single byte (i.e the first ascii character you type in), so gives you a number. You need read_line, which is in ReaderUtil, which Reader can be cast to (I think this is the right way to do it).

After that, you can try to convert the string into an int. Someone might put something other than an int in, though, and to stop everything blowing up, Rust instead returns an option instead - which means it might be there, or might not be. So, you check it with 'is_some', to make sure it's really there, and then can unwrap it to get the juicy, juicy number.

fn main(){
    //First, we read the input line
    let my_number_string = (io::stdin() as io::ReaderUtil).read_line();
    io::println(my_number_string);
    //Then, we try to turn it into an int
    let maybe_my_int = int::from_str(my_number_string);

    if (option::is_some(maybe_my_int)) {
        match option::unwrap(maybe_my_int) {
            0       =>  io::println("zero"),
            1|2     =>  io::println("one or two"),
            3..10   =>  io::println("three to ten"),
            _       =>  io::println("something else")
        }
    } else {
        io::println("Not a number!");
    }
}

bors pushed a commit to rust-lang-ci/rust that referenced this issue May 15, 2021
Fix indexing panic on unicode whitespaces
RalfJung pushed a commit to RalfJung/rust that referenced this issue Apr 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants