如何从标准输入中读取一行? [英] How can I read a single line from stdin?

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

问题描述

我要求等效于 C 中的 fgets().

I'm asking for the equivalent of fgets() in C.

let line = ...;
println!("You entered: {}", line);

我已阅读如何在 Rust 中读取用户输入?,但它询问如何读取多行;我只想要一行.

I've read How to read user input in Rust?, but it asks how to read multiple lines; I want only one line.

我还阅读了我如何阅读单个来自标准输入的字符串?,但我不确定它的行为是否像 fgets()sscanf("%s",...).

I also read How do I read a single String from standard input?, but I'm not sure if it behaves like fgets() or sscanf("%s",...).

推荐答案

如何在 Rust 中读取用户输入? 你可以看到如何遍历所有行:

In How to read user input in Rust? you can see how to iterate over all lines:

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

fn main() {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        println!("{}", line.unwrap());
    }
}

您也可以在没有 for 循环的情况下手动迭代:

You can also manually iterate without a for-loop:

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

fn main() {
    let stdin = io::stdin();
    let mut iterator = stdin.lock().lines();
    let line1 = iterator.next().unwrap().unwrap();
    let line2 = iterator.next().unwrap().unwrap();
}

你不能写一个单行代码来做你想做的事.但以下内容读取一行(与 如何从标准输入中读取单个字符串?):

You cannot write a one-liner to do what you want. But the following reads a single line (and is exactly the same answer as in How do I read a single String from standard input?):

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

fn main() {
    let stdin = io::stdin();
    let line1 = stdin.lock().lines().next().unwrap().unwrap();
}

<小时>

您还可以使用 text_io crate 进行超级简单的输入:


You can also use the text_io crate for super simple input:

#[macro_use] extern crate text_io;

fn main() {
    // reads until a \n is encountered
    let line: String = read!("{}\n");
}

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

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