关于在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。
答案 0 :(得分:20)
以下是您需要执行的操作所需的代码(没有评论它是否是一个很好的方法:
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)
}