检测fgets中的换行符

时间:2013-11-25 17:01:02

标签: c shell prompt fgets

我正在尝试创建一个C程序,用作UNIX系统的简单命令行解释器。我使用fgets()来读取用户输入,然后将输入存储在要解析的缓冲区中。如果唯一的用户输入是按Enter键,我想重新发出提示。有没有办法检测返回键是否是在提示符下输入的唯一键?下面是我到目前为止尝试过的一段代码:

for (;;) {
    printf("$prompt$ ");
    fflush(stdout);

    fgets(commandBuffer, 200, stdin);

    /* remove trailing newline:*/
    ln = strlen(commandLine) - 1;
    if(commandLine[ln] == '\n')
        commandLine[ln] = '\0';

    /* attempt to handle if user input is ONLY return key:*/
    if(commandLine[0] == '\n')
        continue;

3 个答案:

答案 0 :(得分:2)

您需要替换

 if(commandLine[0] == '\n')

if(commandLine[0] == '\0')

上面的代码用nuls替换了换行符。

答案 1 :(得分:1)

ln = strlen(commandLine);
while (ln > 0 && commandLine[ln-1] == '\n')
    --ln;
commandLine[ln] = '\0';

是一种更紧凑的解决方案,可处理空输入等特殊情况。

答案 2 :(得分:0)

ln应该是size_t类型,绝对不应该ln = strlen(commandLine) - 1;。存在许多奇怪的情况,其中ln0commandLine[ln-1]将在commandLine之外访问。执行\n有点像@ensc。

按照@simonc的建议进行测试。

/* remove potential trailing newline */
size_t ln = strlen(commandLine);
if (ln > 0 && commandLine[ln-1] == `\n`) {
  commandLine[--ln] == '\0';
}

/* attempt to handle if user input is ONLY return key:*/
if(commandLine[0] == '\0')
    continue;
相关问题