Logo

Programming-Idioms

  • Fortran
  • Rust
  • JS
  • Elixir

Idiom #120 Read integer from stdin

Read an integer value from the standard input into the variable n

n = String.to_integer IO.gets ""
   integer :: n
   read (*,*) n
use std::io::BufRead;
let n: i32 = std::io::stdin()
    .lock()
    .lines()
    .next()
    .expect("stdin should be available")
    .expect("couldn't read from stdin")
    .trim()
    .parse()
    .expect("input was not an integer");
#[macro_use] extern crate text_io;
let n: i32 = read!();

Can also parse several values and types and delimiters with scan!()

Also see Rust RFC #3183
fn get_input() -> String {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).expect("Failed");
    buffer
}

let n = get_input().trim().parse::<i64>().unwrap();

Change i64 to what you expect to get. Do not use unwrap() if you're not sure it will be parsed correctly.
use std::io;
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();
const {createInterface} = require('readline')

const rl = createInterface ({
  input: process.stdin,
  output: process.stdout
})

rl.question('Input an integer: ', response => {
  let n = parseInt (response)
  // stuff to be done with n goes here

  rl.close()
})

This example only works with nodeJS (server-side JS) because browser JS does not have a standard input.
#include <stdio.h>
int n[15];
fgets(n, 15, stdin);

int n[15]; Int with 15 bytes to use.

Fgets gets user input, and sets n to what it gets

New implementation...