在循环中使用 read_line 时的奇怪行为 [英] Weird behaviour when using read_line in a loop

查看:38
本文介绍了在循环中使用 read_line 时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rust 中的第一个程序应该以字符(C 或 F)的形式接受用户的输入:

My first program in Rust is supposed to take input from the user in the form of characters, either C or F:

use std::io;

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

    let mut switch = true;
    while switch {
        println!("source unit? F or C?");
        io::stdin().read_line(&mut srcunit).expect(
            "failed to read src unit",
        );

        if srcunit.trim() == "F" || srcunit.trim() == "C" {
            println!("doing things right with {}", srcunit);
            switch = false;
        } else {
            println!("either F or C, not {}", srcunit);
        }
    }

    println!("you pressed {}", srcunit);
}

当我启动程序并按 F 或 C 时,它工作正常,所以我在这里跳过这个.当我按下另一个字符时,奇怪的部分出现了.我希望我的程序再次询问 F 或 C,直到我按下这些字符之一.当我这样做时,它应该离开 while 循环并告诉我我按下了什么.

When I start the program and press either F or C, it works right, so I'm skipping this here. The weird part comes when I press another character. I expect my program to ask again for either F or C until I press one of those characters. When I do, it should leave the while loop and tell me what I've pressed.

source unit? F or C?
G
either F or C, not G //so far so good

source unit? F or C?
F
either F or C, not G //why is F not assigned to the srcunit variable? It's supposed to leave the loop now.
F                    //why does it print this line? I didn't press a key or have a println function/macro that does this

source unit? F or C?
V
either F or C, not G //it's still G, wtf
F                    //again, why are those two lines printed? Where does it store, that I pressed F previously?
V

推荐答案

来自 read_line 的文档:

From the documentation for read_line:

读取所有字节,直到到达换行符(0xA 字节),并将它们追加到提供的缓冲区中.

Read all bytes until a newline (the 0xA byte) is reached, and append them to the provided buffer.

(重点是我的.)您需要在阅读下一行之前清除字符串,例如通过调用 clear() 方法在字符串上,否则答案累积在变量中.

(Emphasis mine.) You need to clear the string before reading the next line, for example by calling the clear() method on the string, otherwise the answers are accumulated in the variable.

或者,您可以在循环中定义变量(但这效率稍低,因为这样,String 将无法为下一个答案重用已分配的存储空间,它必须重新分配并重新分配).

Alternatively, you can define the variable in the loop (but this is slightly less efficient because this way, String will not be able to reuse the already allocated storage for the next answer, it has to be deallocated and reallocated again).

另见这个问题,最近被问到.看起来这是一个常见的陷阱.

See also this question, asked recently. Looks like this is a common trap.

这篇关于在循环中使用 read_line 时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆