简体   繁体   中英

C read multiple words/arguments with space from console

Hi I am new to C and I want the user to type something like inspect 2 to show a value of an array at position 2 in that example.

I cant get it to work

    char input[20];
    scanf("%s", input);

    if (strcmp(strtok(input, " "), "inspect") == 0) {
     char str[20];
     int idx;
     printf("input was %s", input);
     idx = sscanf(input, "%s %d", str, &idx);
   }

it always prints input was inspect but the following space and number are not read? What would be the right way to check if the user typed "inspect" and get the index he typed afterwards like I am trying to do?

thank you

You have few choices, and you want to choose one and not mix them up.

For reading the input, consider using the fgets. Much safer, with fewer exceptions to deal with. I've listed the equivalent sscanf, but it's much harder to use. They will both bring in a complete line to 'input'. Notice that the fgets will also include the trailing new line.

   // make buffer large enough.
char input[255] ;

if ( fgets(input, sizeof(input), stdin) != NULL ) {
   ...
}

// OR
if ( sscanf("%19[^\n]", input) = 1 ) {
} ;

For parsing: few options to parse the input` string.

Between the option, I would vote for the sscanf, as it provides the most validation and protection against bad input, overflow, etc. The strcmp(strtok(...)) can easily result in SEGV errors, when strtok returns NULL.

Using sscanf

  if ( sscanf(input, "inspect %d", &idx) ==1 ) {
     ... Show Element idx
  } ;

Using strtok/strcmp

  if ( strcmp(strtok(input, " "), "inspect") == 0 ) {
      if ( sscanf("%d", strtok(NULL, " "), &idx) == 1 ) {
          .. Show element idx
      } ;
  } ;

Using strtol

  if ( strcmp(strtok(input, " "), "inspect") == 0 ) {
      char *stptr = strtok(input, " "), *endptr = NULL ;
      idx = strtol(stptr, &endptr, 10) ;
      if ( endptr != stptr ) {
          .. Show element idx
      } ;
  } ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM