1

I am trying to run the rust executable file but it kept closing immediately.

use std::io::stdin;

fn main() {
    let mut input = String::with_capacity(100);
    stdin().read_line(&mut input).unwrap();
    let v: Vec<i32> = input
        .trim()
        .split_whitespace()
        .map(|x| x.trim().parse().unwrap())
        .collect();
    println!("{:?}", v);
}

This is the program I am trying to run. This is a simple program that accepts numbers from a user from command line and then stores those numbers in a vector and then prints the vector. But the executable closes immediately after I enter all the numbers.

I was wondering if rust had a getchar() function like in c++ to stop the executable from closing immediately.

I am facing a problem similar to the one faced by the user who asked this question in C++.

Aditya
  • 175
  • 9

1 Answers1

2

Well, getchar is not for stopping the executable from closing directly. It is for reading a char. It happens to be a blocking call, so of course it is blocked there. You already used a tool like that, read_line:

use std::io::stdin;

fn main() {
    let mut input = String::with_capacity(100);
    stdin().read_line(&mut input).unwrap();
    let v: Vec<i32> = input
        .trim()
        .split_whitespace()
        .map(|x| x.trim().parse().unwrap())
        .collect();
    println!("{:?}", v);
    stdin().read_line(&mut input).unwrap();
}
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • Thanks for the answer. But what if I don't want to mutate the input string. – Aditya Apr 05 '22 at 20:09
  • 1
    @Aditya, well...just create another string or buffer...Also if it is windows, in the question you post you have some solutions calling some system calls. But it would probably be more convoluted... – Netwave Apr 05 '22 at 20:20
  • 3
    `read_line(&mut String::new())` if you don't need the string. – Chayim Friedman Apr 05 '22 at 21:51