How do i turn a valid string to a i128 in Rust?

176 views Asked by At

(new to rust) I am making a simple program that prints out the numbers between 0 and a number from a terminal argument and i want to turn that number from a string to a i128. What is the neccesary steps to achieve this?

My current code:

use std::env;
fn main()
{
    let args: String = env::args().skip(1).collect::<Vec<String>>().join(" ");
    println!("{}", 0..args.parse::<i128>().unwrap());
}
expecting: (Input: 10)
0
1
2
3
4
5
6
7
8
9
10

got:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: Empty }', src/main.rs:11:40
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
1

There are 1 answers

6
DailyLearner On BEST ANSWER

To get input from the console, use use std::io;. Also you can't print a range using println!() macro, you have to use a for loop to do it.

Note: read_line() doesn't trim the newline character from the input, hence you need to remove the newline character before parsing the input string.

Here is a program to accept input from user and print the range from 0 till user input:

use std::io;

fn main() -> io::Result<()>
{    
    let mut user_input = String::new();
    println!("Enter a number: ");
    let stdin = io::stdin();
    stdin.read_line(&mut user_input)?;    
    let num: i128 = user_input.trim_end().parse().unwrap();
    for x in 0..=num {
        println!("{}", x);
    }
    Ok(())
}