Unexpected value while reading user input from standard input

I am trying to get user input and check if the user types "y" or "n". Surprisingly, in the code below, neither the case of if , nor if else is executed! Apparently, correct_name is neither "y" nor "n". How can it be? Am I doing string conversion incorrectly?

 use std::io; fn main() { let mut correct_name = String::new(); io::stdin().read_line(&mut correct_name).expect("Failed to read line"); if correct_name == "y" { println!("matched y!"); } else if correct_name == "n" { println!("matched n!"); } } 
+7
source share
3 answers

read_line includes the ending line of a newline in the returned line. Add .trim_right_matches("\r\n") to your correct_name definition to remove the ending line of the new line.

+8
source

Instead of trim_right_matches I would recommend using trim_right or better, just trim :

 use std::io; fn main() { let mut correct_name = String::new(); io::stdin().read_line(&mut correct_name).expect("Failed to read line"); let correct_name = correct_name.trim(); if correct_name == "y" { println!("matched y!"); } else if correct_name.trim() == "n" { println!("matched n!"); } } 

This last case handles many types of spaces:

Returns a fragment of a string with leading and trailing spaces removed.

Whitespace is defined according to the conditions of the Unicode White_Space derived kernel property.

Therefore, Windows / Linux / macOS should not matter.


You can also use the truncated length of the result to crop the original String , but in this case you should only use trim_right !

 let trimmed_len = correct_name.trim_right().len(); correct_name.truncate(trimmed_len); 
+12
source

You can use chomp-nl crate , which provides a chomp function that returns a string slice without newline characters.

There is also a trait ChompInPlace if you prefer to do this locally.

Disclaimer: I am the author of this library.

+2
source

Source: https://habr.com/ru/post/1210379/


All Articles