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

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

问题描述

我正在尝试获取用户输入并检查用户输入的是y"还是n".令人惊讶的是,在下面的代码中,ifif 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(" ") 添加到 correct_name 的定义中以删除终止换行符.

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

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

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