1

我做了一个简单的程序,它读取字符直到按下回车键

var data: string

while true:
    var c = readChar(stdin) # read char

    case c
    of '\r': # if enter, stop
    break
    else: discard

    data.add(c) # add the read character to the string

echo data

但是当它尝试时echo data,它崩溃了

> ./program
hello
Traceback (most recent call last)
program.nim(11)          program
SIGSEGV: Illegal storage access. (Attempt to read from nil?)

这意味着data为零。但是每次我按输入一个字符时,它都会将该字符添加到data. 出了点问题,但在哪里?

4

2 回答 2

4

当您将 data 定义为 时,它最初为 nil var data: string。相反,您可以使用var data = ""它来使其成为初始化字符串。

于 2015-09-13T18:10:22.660 回答
1

stdin缓冲所有字符,直到按下换行键,然后它将提交字符。我希望这种行为是阅读直接字符。

这意味着\r永远不会发生这种情况,它会尝试向data但 data is添加一个字符nil,因此失败。我认为它在echo声明中失败了。

为了演示,此代码有效:

var data = ""

while true:
    var c = readChar(stdin) # read char

    case c
    of '\e': # if escape, stop
        break
    else:
        data.add(c) # add the read character to the string

echo data
于 2015-09-14T09:28:43.460 回答