1

I am having trouble while taking integer and float input directly.

I am beginner to Rust and having problem while taking integer input. I did some research but I did not find a direct way of taking integer input as in C++. I just want to know that is there any other possible way of taking integer input without taking string input and than shadowing.

let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Error");
let input:i16 = input.trim().parse().unwrap();
M Saad Sajid
  • 443
  • 1
  • 3
  • 9
  • Publish your own library that simplifies this. – SOFe Aug 19 '19 at 06:11
  • `cin >> input` is wrong and you should pretty much never use it. Read [me ranting about why C++'s input model is bad](https://users.rust-lang.org/t/why-is-it-so-difficult-to-get-user-input-in-rust/27444/11) in a related URLO thread. – trent Aug 19 '19 at 11:07

2 Answers2

2

You have the option to use the text_io crate to achieve your goal.

You must include the crate name and version in Cargo.toml file

[dependencies]
text_io = "0.1.7"

Here is the working example that you want.

#[macro_use] 
extern crate text_io;
fn main() {
    let i: i32 = read!();
    print!("{}",i);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Fahim Uz Zaman
  • 444
  • 3
  • 6
  • 1
    This solution does not check for non-integer input and will panic if non-integer input is provided. This is equivalent to the unwrap() call in the OP's question. – Gardener Aug 19 '19 at 14:03
1

@Faheem Uz Zaman suggested using the text_io crate, which is an excellent option. However, the read! macro really does exactly what the code in the original question does: reads an input into a string variable and then attempts to parse that string into an i32.

In order to parse input from the terminal into an i32 variable, some error-handling needs to be implemented. The code in the question is complete and handles integer input, so long as the input is indeed an integer.

The text_io crate provides a try_read! macro which allows for bad input. Here is an example of how to implement the try_read! macro, which requires adding the same type of error handling that could be added to the original question's sample code:

use text_io::*;
fn main() {

    let i: i32 = match(try_read!()) {
        Ok(integer_read) => integer_read,
        Err(bad_string) => {
            eprintln!("Error: {}", bad_string);
            return;
        },
    };
    println!("{}",i);
}

This could be shortened using the ? operator, which would require an adjustment to the return value for main():

use text_io::*;
fn main()-> Result<(), Error>{
    let i: i32 = try_read!()?;
    println!("{}",i);
    Ok(()) 
}

This will print the parsing error message if the input is not parseable to an i32.

Gardener
  • 2,591
  • 1
  • 13
  • 22