Skip to content

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

Closed
@ghost

Description

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

Activity

AngryLawyer

AngryLawyer commented on Sep 13, 2012

@AngryLawyer

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!");
    }
}
added a commit that references this issue on May 15, 2021

Merge pull request rust-lang#3479 from sinkuu/issue_2995

f70ce00
added a commit that references this issue on Apr 20, 2024

Auto merge of rust-lang#3479 - rust-lang:rustup-2024-04-17, r=RalfJung

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @catamorphism@AngryLawyer

        Issue actions

          When I read the number by read_byte, it prints I guess ASCII number.. · Issue #3479 · rust-lang/rust