如何从标准输入读取单个字符串? [英] How do I read a single String from standard input?

查看:86
本文介绍了如何从标准输入读取单个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::io 文档,但我认为这应该可行:

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();

但我收到此错误:

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.

I'm using a nightly Rust v1.0.

推荐答案

以下是执行您正在尝试的操作所需的代码(不评论是否是一个好的方法:

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

如果您想更好地控制读取行的位置,可以使用 Stdin::read_line.这接受要附加到的 &mut String.有了这个,你可以确保字符串有足够大的缓冲区,或者附加到现有的字符串:

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

这篇关于如何从标准输入读取单个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆