如何从 stdin 读取一行?

How can I read a single line from stdin?

我要的是 C 中的 fgets() 等价物。

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

我已经阅读了How to read user input in Rust?,但它询问如何阅读多行;我只想要一根线。

我也读过 ,但我不确定它的行为是否像 fgets()sscanf("%s",...)

How to read user input in Rust? 中您可以看到如何遍历所有行:

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

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

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

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

你不能写一行来做你想做的事。但是以下内容只读了一行(与 中的答案完全相同):

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

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

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

#[macro_use] extern crate text_io;

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

如果您真的想要 fgets,那么 , you should use Stdin::read_line。此方法接受一个缓冲区,您可以更好地控制将字符串放入:

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

fn main() {
    let mut line = String::new();
    let stdin = io::stdin();
    stdin.lock().read_line(&mut line).unwrap();
    println!("{}", line)
}

与 C 不同,您不会意外地溢出缓冲区;如果输入的字符串太大,它会自动调整大小。

是您大多数时候会看到的惯用解决方案。在里面,字符串是为你管理的,界面也干净多了。

stdin 中读取一行:

    let mut line = String::new();
    std::io::stdin().read_line(&mut line)?; // including '\n'

您可以使用 line.trim_end()

删除 '\n'

读到 EOF:

    let mut buffer = String::new();
    std::io::stdin().read_to_string(&mut buffer)?;

使用隐式同步:

use std::io;
fn main() -> io::Result<()> {
    let mut line = String::new();
    io::stdin().read_line(&mut line)?;

    println!("You entered: {}", line);
    Ok(())
}

使用显式同步:

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

fn main() -> io::Result<()> {
    let stdin = io::stdin();
    let mut handle = stdin.lock();

    let mut line = String::new();
    handle.read_line(&mut line)?;

    println!("You entered: {}", line);
    Ok(())
}

如果您对字节数感兴趣,例如n,使用:
let n = handle.read_line(&mut line)?;

let n = io::stdin().read_line(&mut line)?;

试试这个:

use std::io;
fn main() -> io::Result<()> {
    let mut line = String::new();
    let n = io::stdin().read_line(&mut line)?;

    println!("{} bytes read", n);
    println!("You entered: {}", line);
    Ok(())
}

doc

如果您想在某个时候离开 for-循环

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

fn main() {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        match line {
            Err(_) => break,    // with ^Z
            Ok(s) => println!("{}", s),
        }

    }
    println!("fin");
}