Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a single String from standard input?

Tags:

string

stdin

rust

There isn't straightforward instruction on receiving a string as a variable in the std::io documentation, but I figured this should work:

use std::io;
let line = io::stdin().lock().lines().unwrap();

But I'm getting this error:

src\main.rs:28:14: 28:23 error: unresolved name `io::stdin`
src\main.rs:28          let line = io::stdin.lock().lines().unwrap();
                                   ^~~~~~~~~

Why?

I'm using a nightly Rust v1.0.

like image 492
andrey Avatar asked Feb 15 '15 17:02

andrey


People also ask

How can we read from standard input in Java?

The standard input(stdin) can be represented by System.in in Java. The System.in is an instance of the InputStream class. It means that all its methods work on bytes, not Strings. To read any data from a keyboard, we can use either a Reader class or Scanner class.

What does it mean to read from standard input?

Short for standard input, stdin is an input stream where data is sent to and read by a program.


Video Answer


1 Answers

Here's the code you need to do what you are trying (no comments on if it is a good way to go about it:

use std::io::{self, BufRead};

fn main() {
    let stdin = io::stdin();
    let line = stdin.lock()
        .lines()
        .next()
        .expect("there was no next line")
        .expect("the line could not be read");
}

If you want more control over where the line is read to, you can use Stdin::read_line. This accepts a &mut String to append to. With this, you can ensure that the string has a large enough buffer, or append to an existing string:

use std::io::{self, BufRead};

fn main() {
    let mut line = String::new();
    let stdin = io::stdin();
    stdin.lock().read_line(&mut line).expect("Could not read line");
    println!("{}", line)
}
like image 166
Shepmaster Avatar answered Sep 22 '22 16:09

Shepmaster