You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust字符串匹配问题:简易待办列表输入匹配失败求助

Rust待办列表匹配问题修复

核心问题:输入匹配失败

read_line会把用户输入的换行符(\n或\r\n)一起读进字符串里,你调用了input.trim_end()但没把结果存回input,导致input实际是"1\n"这类带换行的字符串,根本匹配不上"1"/"2"/"3"。

其他需要修复的问题

  • 递归调用main()会导致栈溢出,应该用循环替代
  • 显示列表时while i <= todo.len()会触发索引越界(向量的有效索引是0到len-1)
  • 添加待办项时,输入的字符串带换行符,存进去会有多余空白
  • 删除待办项时,输入的数字带换行符,解析前得先处理;直接用unwrap()会在输入非数字时崩溃

修改后的完整代码

use std::io::{self, stdin};

fn main() {
    let mut todo = Vec::new();

    loop {
        println!("--TODO LIST--");
        println!();
        println!("1. Show List");
        println!("2. Add to list");
        println!("3. Remove from list");
        println!("4. Exit"); // 新增退出选项,避免无限循环

        let mut input = String::new();
        stdin().read_line(&mut input).expect("Failed to read input");
        // 去除末尾空白(包括换行符)并重新赋值
        let input = input.trim_end();

        match input {
            "1" => {
                if todo.is_empty() {
                    println!("List is empty!");
                    continue;
                }
                // 从1开始显示序号,避免索引越界
                for (index, item) in todo.iter().enumerate() {
                    println!("{}. {}", index + 1, item);
                }
            }
            "2" => {
                println!("What do you want to add?");
                let mut add = String::new();
                io::stdin().read_line(&mut add).expect("Failed to read input");
                // 去除换行符后存入
                let add = add.trim_end().to_string();
                if !add.is_empty() {
                    todo.push(add);
                    println!("Added successfully!");
                } else {
                    println!("Cannot add empty item!");
                }
            }
            "3" => {
                if todo.is_empty() {
                    println!("List is empty, nothing to remove!");
                    continue;
                }
                println!("What do you want to remove (number)");
                let mut remove_input = String::new();
                io::stdin().read_line(&mut remove_input).expect("Failed to read input");
                // 去除换行符后解析数字
                match remove_input.trim_end().parse::<usize>() {
                    Ok(num) => {
                        // 用户输入的是1开始的序号,转成0索引
                        if num > 0 && num <= todo.len() {
                            todo.remove(num - 1);
                            println!("Removed successfully!");
                        } else {
                            println!("Invalid number, out of range!");
                        }
                    }
                    Err(_) => {
                        println!("Please enter a valid number!");
                    }
                }
            }
            "4" => {
                println!("Exiting...");
                break;
            }
            _ => {
                println!("No Match, please enter 1-4!");
            }
        }
        println!(); // 分隔每次操作的输出
    }
}

关键修改说明

  1. 修复输入匹配:用let input = input.trim_end();获取去除末尾空白的字符串,确保匹配纯数字
  2. 替换递归为循环:用loop包裹主逻辑,递归调用main()会不断创建栈帧,最终导致栈溢出
  3. 修正列表显示:用enumerate()遍历,序号从1开始,既符合用户习惯又避免索引越界
  4. 处理输入空白:添加和删除时都对输入做trim_end(),去除多余的换行符
  5. 增加错误处理:删除时用match处理parse结果,同时检查输入的序号是否在有效范围内,避免程序崩溃
  6. 新增退出选项:添加"4. Exit"让用户可以正常退出程序

内容的提问来源于stack exchange,提问作者Alex Biedermann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 14:56:08