peterxu422 wrote
When implementing readLine() in Keyboard class, we don't know the length of the string ahead of time, so what's the best way to go about this?
The simplest thing to do is to pick an arbitrary maximum response length, say 80 characters, and always allocate an 80 character string and discard and do not echo any characters that cannot be appended to the string.
Another approach is to allocate a single larger string in Keyboard.init(), perhaps 250 characters -- enough for a bit more than a 3 line response -- and read into that string. When you get the new-line, you can allocate a string that is exactly the required length and copy the response data into it.
An even more sophisticated approach would be to initially allocate a smaller buffer in Keyboard.init() and if the user ever types more than will fit in the buffer, allocate a new and bigger buffer, copying the already read data into the new buffer before destroying the old buffer. This way a minimal amount of extra memory will be used unless the user types a long response, but you do not incur the overhead of allocating and freeing memory blocks for each character typed.
--Mark