【问题标题】:How do I read a single String from standard input?如何从标准输入中读取单个字符串?
【发布时间】:2015-02-15 17:38:24
【问题描述】:

std::io documentation 中接收字符串作为变量并没有直接的说明,但我认为这应该可行:

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

但是我收到了这个错误:

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

为什么?

我正在使用夜间 Rust v1.0。

【问题讨论】:

  • @Shepmaster 是的,但我认为'old_io' 意味着它是一个已弃用的功能。是不是反过来?
  • 您所指的文档是针对第一个 alpha 版本的。然后名为io 的模块在 发布后重命名为old_io,它确实即将淘汰,但尚未完全被新的io 模块取代。首先你需要弄清楚你的立场:你是在使用 1.0.0-alpha 还是在跟踪夜间?

标签: string rust stdin


【解决方案1】:

这是您尝试做的事情所需的代码(如果这是一个好方法,请不要打开 cmets:

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

如果您想更好地控制读取行的位置,可以使用Stdin::read_line。这接受 &mut 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)
}

【讨论】:

  • read_line() 示例中,使用.ok().expect() 模式作为返回值不是更合适吗?你没有对unwrap()ped 值做任何事情。
  • @tilde 我不知道 more 是否合适,但我也不认为 less 合适。当您unwrapResult 时,错误值将用作紧急消息。对于您的示例,您需要为 expect 提供错误消息,这可能更适合您的用例。
  • 我没有想到错误值会传播到恐慌中,感谢您的澄清!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 2019-09-17
  • 2021-06-19
  • 2021-06-18
相关资源
最近更新 更多