从stdin读取用户输入时,为什么我的字符串不匹配? [英] Why does my string not match when reading user input from stdin?

查看:75
本文介绍了从stdin读取用户输入时,为什么我的字符串不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取用户输入,并检查用户输入的是 y还是 n。令人惊讶的是,在下面的代码中, if if else 情况都没有执行!显然, correct_name 既不是 y也不是 n。怎么可能?我是在做字符串转换错误还是什么?

I'm trying to get user input and check if the user put in "y" or "n". Surprisingly, in the below code, neither the if nor the if else case executes! Apparently, correct_name is neither "y" nor "n". How can that be? Am I doing my string conversion wrong or something?

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


推荐答案

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

read_line includes the terminating newline in the returned string. Add .trim_right_matches("\r\n") to your definition of correct_name to remove the terminating newline.

这篇关于从stdin读取用户输入时,为什么我的字符串不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆