Weird behaviour when using read_line in a loop

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.

Leave a Comment