为什么我的stdin用户输入没有正确匹配?

Joe*_*Joe 8 rust

我正在尝试获取系统输入并检查用户是否输入了是或否.我的字符串转换是错误还是什么?if块不执行.

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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 12

而不是trim_right_matches,我建议使用trim_right甚至更好,只是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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

最后一种情况处理许多类型的空白:

返回删除了前导和尾随空格的字符串切片.

'Whitespace'是根据Unicode派生核心属性White_Space的术语定义的.

所以Windows/Linux/macOS无关紧要.


你也可以使用修剪结果的长度来截断原文String,但在这种情况下你应该只使用trim_right!

let trimmed_len = correct_name.trim_right().len();
correct_name.truncate(trimmed_len);
Run Code Online (Sandbox Code Playgroud)


win*_*ner 8

read_line包括返回字符串中的终止换行符.添加.trim_right_matches("\r\n")到您的定义中correct_name以删除终止换行符.

  • 你不应该需要`as_slice`,因为`String`实现了'Deref <Target = str>`.`let line = io :: stdin().read_line(); let trimmed = line.trim_right_chars(..);`应该工作. (2认同)
  • 我建议只使用[`trim`](http://doc.rust-lang.org/std/str/trait.StrExt.html#tymethod.trim)或[`trim_right`](http:// doc.rust-lang.org/std/str/trait.StrExt.html#tymethod.trim_right)而不是担心跨平台的换行符:-) (2认同)