Brandon White Brandon White - 2 months ago 13
C Question

Determining multiple space separated inputs in C buffer

I have been trying to justify my logic while reading in input for my command interpreter. The problem I am running into is

strstr()
either is not accepting
"%s"
as a needle or is treating the entire haystack as a string and disregarding spaces, newlines, etc because of this.

char command[4] = "";
char arg1[512] = "";
char arg2[512] = "";
char tmp[1029] = "";
char buffer[BUFFERSIZE];
memset(buffer, '\0', BUFFERSIZE);

while(fgets(buffer, BUFFERSIZE, stdin) != NULL){
strcpy(command, "");
strcpy(arg1, "");
strcpy(arg2, "");
strcpy(tmp, "");
if(strstr(buffer, "%s\n") != NULL)
sscanf(buffer, "%s", command); // 0 arguments
if(strstr(buffer, "%s %s") != NULL)
sscanf(buffer, "%s", arg1); // 1 argument
if(strstr(buffer, "%s %s %s") != NULL)
sscanf(buffer, "%s", arg2); // 2 arguments
printf("%s %s %s\n", command, arg1, arg2);
}


No matter what I input:


  • com

  • val argument1val

  • cmd arg1 arg2val

  • etc



I always end up with empty character arrays for
command
,
arg1
, and
arg2
.

My input will always be a single string or up to three space separated strings followed by a newline character.

Answer

You just have to scan once and check for number of parsed arguments that sccanf returns (with special check for empty line entered)

#include <stdio.h>
#include <strings.h>

#define BUFFERSIZE 2000

int main()
{
int nb_args;
char command[4] = "";
char arg1[512] = "";
char arg2[512] = "";
char buffer[BUFFERSIZE];
memset(buffer, '\0', BUFFERSIZE);

while(fgets(buffer, BUFFERSIZE, stdin) != NULL){
    strcpy(command, "");
    strcpy(arg1, "");
    strcpy(arg2, "");

    nb_args = sscanf(buffer, "%3s%511s%511s", command,arg1,arg2);
    if (strlen(command)==0)
    {
        printf("empty line\n");
    }
    else
    {
    switch(nb_args)
    {
        case 1:
           printf("Command = %s\n",command);
           break;
        case 2:
           printf("Command = %s, arg1 = %s\n",command,arg1);
           break;
        case 3:
           printf("Command = %s, arg1 = %s, arg2 = %s\n",command,arg1,arg2);
           break;
    }
    }
}
}
Comments