温馨提示:本文翻译自stackoverflow.com,查看原文请点击:rust - Why does my string not match when reading user input from stdin?
conditional-statements rust string user-input

rust - 从stdin读取用户输入时,为什么我的字符串不匹配?

发布于 2020-04-05 20:25:40

我正在尝试获取用户输入,并检查用户是否输入了“ y”或“ n”。令人惊讶的是,在下面的代码中,the ifif elsecase 都不执行!显然,correct_name既不是“ y”也不是“ n”。这个怎么可能?我是在做字符串转换错误还是什么?

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

查看更多

提问者
Joe
被浏览
107
9,873 2015-01-07 02:38

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