How to ignore the line break while printing a string read from stdin?

后端 未结 2 920
梦谈多话
梦谈多话 2021-01-14 05:07

I tried to write a bit of code which reads a name from stdin and prints it. The problem is the line breaks immediately after printing the variable and the characters followi

相关标签:
2条回答
  • 2021-01-14 05:41

    If you want to remove the last character only (in this case is newline character), you should use .pop() instead of .trim().

    When you use .trim(), the leading and trailing whitespace(s) will be removed, so the space, tab, newline, and the other whitespace in the beginning and the end of the string will be removed.

    use std::io;
    
    fn main() {
        println!("Enter your name:");
        let mut name = String::new();
        io::stdin().read_line(&mut name).expect("Failed To read Input");
        name.pop();
        println!("Hello '{}'!", name);
    }
    
    0 讨论(0)
  • 2021-01-14 05:52

    Use .trim() to remove whitespace on a string. This example should work.

    use std::io;
    
    fn main() {
        println!("Enter your name:");
        let mut name = String::new();
        io::stdin().read_line(&mut name).expect("Failed To read Input");
        println!("Hello '{}'!", name.trim());
    }
    

    There also trim_start() and .trim_end() if you need to remove whitespace changes from only one side of the string.

    0 讨论(0)
提交回复
热议问题