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.
code:
main{
let mut player_name=String::new();
io::stdin().read_line( &mut player_name)
.expect("Failed to read line");
player_data(player_name);
}
fn player_data(player:String){
let mut names:Vec= Vec::new();
names.push(player);
println!("player names are {:?}",names)
}
output:
Enter Your Name
siraj
player names are ["siraj\n"]
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.
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");
input.trim().to_string()
}
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: