【问题标题】:Why does a string read from stdin never match the strings I compare it to? [duplicate]为什么从标准输入读取的字符串与我比较的字符串不匹配? [复制]
【发布时间】:2019-05-04 03:10:01
【问题描述】:

我正在尝试使用此代码在用户提供的字符串上match

use std::io;

fn main() {
    let mut input = String::new();

    io::stdin().read_line(&mut input).expect("Failed to read line.");

    match input.as_ref(){
        "test" => println!("That was test"),
        _ => print!("Something's wrong"),
    }
}

但是,即使我输入“test”,这段代码也总是显示“Something's wrong”。我怎样才能使这项工作按预期进行?

【问题讨论】:

  • “这不起作用”不是问题描述。你有错误吗?哪个?你得到意外的输出吗?你期待哪一个?
  • 尝试input.trim().as_ref() 摆脱拖尾换行符
  • 是的,我的问题是意外输出。这段代码没有按我的意愿工作。总是给我“有问题”

标签: rust


【解决方案1】:

这与"test" 不匹配,即使(看起来)您输入了"test",因为您还通过按Enter 输入了一个新行,所以input 实际上将包含"test\n"

您可以通过使用trim_end 删除尾随换行符来解决此问题:

match input.trim_end() {
    "test" => println!("Great!"),
    _ => println!("Too bad")
}

不过,这不会修改原始字符串。

【讨论】:

  • 谢谢先生。这解决了我的问题。
猜你喜欢
  • 2016-11-05
  • 2022-03-30
  • 2015-03-02
  • 2015-10-11
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多