【问题标题】:Comparing a string against a string read from input does not match in Rust [duplicate]比较字符串与从输入读取的字符串在 Rust 中不匹配 [重复]
【发布时间】:2016-11-05 09:59:56
【问题描述】:

在下面的代码中,我原以为用户输入“q”时会打印“wow”消息,但事实并非如此。

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input)
        .expect("failed to read line");

    if input == "q" {
       println!("wow") ;
    }
}

为什么没有按预期打印消息?

【问题讨论】:

    标签: string io rust


    【解决方案1】:

    您的输入字符串包含一个尾随换行符。使用trim 删除它:

    use std::io;
    
    fn main() {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read line");
    
        if input.trim() == "q" {
            println!("wow") ;
        }
    }
    

    您可以通过打印输入的值自己看到这一点

    println!("{:?}", input);
    
    $ ./foo
    q
    "q\n"
    

    【讨论】:

      猜你喜欢
      • 2019-05-04
      • 2018-01-15
      • 2019-12-22
      • 1970-01-01
      • 2022-03-30
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多