Search code examples
cscanf

How to input just one at scanf?


char command[6];
int command_num=0;
scanf("%s %d", command, &command_num);

If command is "top", I want to input only command, not command_num. But when i input just command, input is continue. How can I solve this?


Solution

  • Your description is basically pseudo code, just translate it to C:

    char command[LARGE_ENOUGH]; // probably no reason to allocate just 6 bytes
    
    if(scanf("%s", command) != 1) // read only command and check result
    { 
      /* handle error - abort program etc */
    }
    
    if(strcmp(command, "top") != 0) // if command wasn't top
    {
      if(scanf("%d", &command_top) != 1)
      {
        /* handle error - abort program etc */
      }
    }
    

    Place this all in a while loop if needed.

    However, a better solution might be to take the input as string and accept digits in the string as commands.