Logo

Programming-Idioms

  • C++
  • Rust

Idiom #120 Read integer from stdin

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

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();
#[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
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");
#include <iostream>
std::cin >> n;
#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...
< >
programming-idioms.org