在fgets中检测换行[重复]

问题描述 投票:1回答:3

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

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;
c shell prompt fgets
3个回答
2
投票

您需要更换

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

with

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

此代码上方的代码将换行符替换为nul。


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

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


-1
投票

一个流行的单线删除潜在的新行是

if (fgets(commandBuffer, 200, stdin)) {
  commandBuffer[strcspn(commandBuffer, "\n")] = '\0';

[strlen(commandLine)返回0时,下面出现问题。当读取输入行以空字符开头时,会发生这种情况。

fgets(commandBuffer, 200, stdin);
ln = strlen(commandLine) - 1;  // ln could be outside 0...199  
if(commandLine[ln] == '\n')    // commandLine[ln] is then undefined behavior 

否则执行@ensc

if (fgets(commandBuffer, 200, stdin)) {
  ln = strlen(commandLine);
  while (ln > 0 && commandLine[ln-1] == '\n') {
    --ln;
  }
  commandLine[ln] = '\0';
© www.soinside.com 2019 - 2024. All rights reserved.