Input shows enter ./n

when i take user input and save it to a vector ,as i take input and press enter vector also shows enter /n with the input taken.. how to resolve this issue.
let mut player_name=String::new();
io::stdin().read_line( &mut player_name)
.expect("Failed to read line");

fn player_data(player:String){
let mut names:Vec= Vec::new();
println!("player names are {:?}",names)


Enter Your Name
player names are ["siraj\n"]

  1. Please format your post according to the pinned thread.
  2. Does the documentation for read_line help?

pinned thread?

Looks like it isn't pinned if you already read it once, sorry. I mean this:

Note that you can edit your own prior posts. Please do so as a courtesy to the many participants of this forum, who are more likely to help if the post follows forum conventions.

1 Like

The issue is that read_line appends a newline character to the end of the string. If you want to remove it, you can use trim, which removes whitespace from both ends, or trim_end, which removes trailing whitespace only:

use std::io;

fn input() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("cannot read line");


Alternatively, you can use BufRead::lines:

use std::io::{self, prelude::*};

fn input() -> String {
        .and_then(|res| res.ok())
        .expect("cannot read line")

This approach is better IMO for reading a line, since it

  • avoids reinventing the wheel;

  • removes only the trailing newline character, not all trailing whitespace, and is thus more semantically accurate (note that you can still add a .trim() to the chain if you additionally want to discard whitespace);

  • avoids the explicit creation of a mut variable;

  • avoids an extra allocation (you can of course check for a newline character and use pop in the first approach, but that would be more verbose; see the first bullet);

  • allows you to differentiate between EOF and other kinds of I/O error, as shown below:

    // returns None for EOF
    fn input() -> Option<String> {
            .map(|res| res.expect("cannot read line"))

Also, if you want to print information for the user of the program, you probably want to iterate and use {} formatting instead of {:?}:

println!("Player names are:");
for name in player_names {
    println!("{}", name);

{} is for displaying information to the user (it uses the Display trait), {:?} is for debugging (it uses the Debug trait).

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.