Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 从stdin读取用户输入时,为什么我的字符串不匹配?_String_Rust_Conditional Statements_User Input - Fatal编程技术网

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

String 从stdin读取用户输入时,为什么我的字符串不匹配?,string,rust,conditional-statements,user-input,String,Rust,Conditional Statements,User Input,我正在尝试获取用户输入,并检查用户是否输入了“y”或“n”。令人惊讶的是,在下面的代码中,if和if-else案例都没有执行!显然,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 l

我正在尝试获取用户输入,并检查用户是否输入了“y”或“n”。令人惊讶的是,在下面的代码中,
if
if-else
案例都没有执行!显然,
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!");
    }
}

read\u line
在返回的字符串中包含终止换行符。将
.trim\u right\u matches(“\r\n”)
添加到
的定义中,更正\u name
以删除终止换行符。

我建议使用或更好,而不是:

最后一个案例处理大量类型的空白:

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

“Whitespace”是根据Unicode派生的核心属性whiteu Space的术语定义的

因此,Windows/Linux/macOS应该无关紧要


您也可以使用修剪结果的长度来截断原始的
字符串
,但在这种情况下,您应该只使用
trim_right

let trimmed_len = correct_name.trim_right().len();
correct_name.truncate(trimmed_len);
您可以使用,它提供返回不带换行符的字符串片段的

如果您愿意在适当的位置执行此操作,还有一个解决方案


免责声明:我是此库的作者。

Windows应该是“\r\n”吗?当我添加时,它告诉我bool`不是为类型`&str实现的,我在查看文档后意识到它必须放在if语句中。谢谢由于
String
实现了
Deref
,因此您不需要使用
as\u slice
<代码>让线=io::stdin()。读取线();let trimmed=直线。trim_right_chars(..)应该有效。我建议只使用或不使用跨平台换行符:-)trim/
trim\u right
/
trim\u right\u matches
?这是使用
trim\u right\u matches
函数的,所以chomp函数是一个快捷方式。使用
truncate
思想进行就地修剪也有一个特点。因此,主要的好处是有一个更短的方法来修剪换行符。
let trimmed_len = correct_name.trim_right().len();
correct_name.truncate(trimmed_len);