相关疑难解决方法(0)

比较Rust中的字符串

我想比较一个从stdin输入的字符串到一个没有运气的静态字符串.

这是我到目前为止所尝试的:

fn main() -> () {
    let mut line = "".to_string();
    let exit = "exit".to_string(); 

    while line.as_slice() != exit.as_slice() {
        let input = std::io::stdin().read_line().ok();

        line.push_str( input.unwrap().to_string().as_slice() );

        assert_eq!(line, exit);
    }   
}
Run Code Online (Sandbox Code Playgroud)

但是在断言期间失败了.我应该如何将字符串输入与Rust中的静态字符串进行比较?

非常感激您的帮忙.

rust

9
推荐指数
1
解决办法
1万
查看次数

为什么我的stdin用户输入没有正确匹配?

我正在尝试获取系统输入并检查用户是否输入了是或否.我的字符串转换是错误还是什么?if块不执行.

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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

rust

8
推荐指数
2
解决办法
1646
查看次数

标签 统计

rust ×2