'How to stop .exe file from closing immediately?

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++.



Solution 1:[1]

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();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Netwave