rust - 不比较 Rust 中的字符串

标签 rust

<分区>

我已经接受了用户的输入,但是当我尝试比较时,它没有输入 if 或 else if block 。相反,它转到其他 block

use std::io;

fn main() {
    let small_coffee = 2;
    let medium_coffee = 4;
    let large_coffee = 6;

    let mut total_price = 0;

    let mut user_choice = String::new();
    io::stdin().read_line(&mut user_choice).ok().expect("Eror");

    if user_choice == "1" {
        total_price += small_coffee;
    } else if user_choice == "2" {
        total_price += medium_coffee;
    } else if user_choice == "3" {
        total_price += large_coffee;
    } else {
        println!("Sorry! Invalid Choice");
    }

    println!("Your total bill amounted to : {}$", total_price);
}

最佳答案

This function will read bytes from the underlying stream until the newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf.

使用trim() , let input = user_choice.trim();

关于rust - 不比较 Rust 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57522953/

相关文章:

data-structures - 用另一种数据结构在Rust中初始化数据结构的字段

rust - 重复更新和输出数据结构

rust - 为什么通过指向移动变量的指针写入在 Rust 中没有被确定为 UB?

rust - 在 Rust 中与闭包和生命周期作斗争

rust - 为什么通过提取方法进行重构会触发借用检查器错误?

pointers - 接受字符串引用的函数参数是否直接指向字符串变量或 Rust 堆上的数据

macos - 为什么Rust会发出280行汇编代码来打印 “Hello, world”?

rust - 可变借用不止一次

generics - "generic parameters of trait function"和 "generic parameters of trait"有什么区别?

rust - 使用构建器模式的所有权错误