Weird behaviour when using read_line in a loop

后端 未结 1 1655
一个人的身影
一个人的身影 2020-12-04 02:10

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 = St         


        
相关标签:
1条回答
  • 2020-12-04 02:23

    From the documentation for read_line:

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

    (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.

    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.

    0 讨论(0)
提交回复
热议问题