14

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.

3
  • Have you read The Rust Book's section on standard input? Commented Feb 15, 2015 at 17:43
  • @Shepmaster Yes, but I figured 'old_io' means it's a deprecated feature. Is it other way around? Commented Feb 15, 2015 at 17:48
  • 2
    The documentation you are referring to is for the first alpha release. The module then called io was renamed old_io after that release, and it is indeed on the way out, but not yet completely superseded by the new io module. First you need to figure out where you stand: Are you using 1.0.0-alpha or are you tracking nightlies? Commented Feb 15, 2015 at 18:36

1 Answer 1

25

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

in the read_line() example, wouldn't it be more appropriate to use .ok().expect() pattern for the return value? You're not doing anything with the unwrap()ped value.
@tilde I don't know about more appropriate, but I don't think it would be less appropriate either. When you unwrap a Result, the error value will be used as the panic message. With your example, you'd need to provide an error message for expect, which might be more appropriate for your use case.
I didn't think about the fact that the error value would be propagated to the panic anyways, thanks for the clarification!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.