Print! macro still create a new line

use std::io;

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

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

    print!("Your input: {}, hello world!", guess);
}

The results of the above code always appear in the form below.

Your input: 12
, hello world!

but i want result like below.

Your input: 12, hello world!

How can I fix it?

It's because read_line(&mut guess) includes the trailing line break in the string value that is written to guess. You could trim the string before printing to get rid of the line break.

use std::io;

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

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

-   print!("Your input: {}, hello world!", guess);
+   print!("Your input: {}, hello world!", guess.trim());
}
4 Likes

Thank you very much. I couldn't find this answer anywhere on the web. :star_struck:

I’d recommend to use trim_end :slight_smile:

2 Likes

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.