1

I am attempting to create a C program to be used as a simple command line interpreter for a UNIX system. I use fgets() to read user input which then stores input in a buffer to be parsed. If the only user input is pushing enter, I would like to reissue the prompt. Is there a way to detect if the return key was the only key entered at the prompt? Below is a snippet of code I have tried so far:

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;
trawww
  • 103
  • 1
  • 6
  • 14

3 Answers3

1

You need to replace

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

with

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

The code just above this replaces newlines with nuls.

simonc
  • 41,632
  • 12
  • 85
  • 103
1
ln = strlen(commandLine);
while (ln > 0 && commandLine[ln-1] == '\n')
    --ln;
commandLine[ln] = '\0';

is a more compact solution handling special cases like empty input.

ensc
  • 6,704
  • 14
  • 22
0

A popular one-liner to remove a potential new line is

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

The below suffers a problem when strlen(commandLine) returns 0. This happen when the input line read begins with a null character.

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

Otherwise perform like @ensc.

if (fgets(commandBuffer, 200, stdin)) {
  ln = strlen(commandLine);
  while (ln > 0 && commandLine[ln-1] == '\n') {
    --ln;
  }
  commandLine[ln] = '\0';
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256