7

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 following the variable are printed in the next line:

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

The '!' is printed in the next line, which is not the expected location.

enter image description here

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Sriram
  • 173
  • 2
  • 12

2 Answers2

10

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
4e554c4c
  • 478
  • 3
  • 12
  • 1
    io::stdin().read_line() does not preprocess the line read, so a '\n' remains at the end. So it needs the extra trim() call, though ideally read_line() as it name suggests should do this by itself in order to provide better api to users. – creativcoder Apr 27 '17 at 06:00
0

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);
}
Andra
  • 1,282
  • 2
  • 11
  • 34