How much bytes does read_line().expect() return in rust?

I've entered a string hello. Why does expect() return 6 bytes? Because expect() also takes into account the \n symbol?

Yes, with read_line, the line break is generally included. I believe if stdin is getting closed early and read_line reaches EOF, you can get a final line without a line break, too.

1 Like

I found this in the documentation

This function (read_line()) will read bytes from the underlying stream until the newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf .

It turns out that the newline character appears in the line where the reading occurs. Right?

Example:

    let mut user_input = String::new(); // will contain a `\n` after writing `hello`
    io::stdin().read_line(&mut user_input); // entered `hello` and pressed the Enter
1 Like

It turns out I understood correctly

use std::io;

fn main() {
    println!("Please input your string");

    let mut user_input = String::new();

    let result = io::stdin().read_line(&mut user_input).expect("Failed to read line"); // hello

    println!("result = {result}"); // 6
    println!("user_input_len = {}", user_input.len()); // 6
}

See this Rust Playground - it fails on the input, but you can use trim to remove the whitespace and make it parse.

I looked at the trim documentation and deleted the question) Thank you

Using stdin().lines() will give you an iterator over the lines without the newline, at a slight performance cost since you can't reuse the String.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.