-3

I am having difficulty scanning from user input an integer (and storing it) only if printed directly after a !:

   char cmd[MAX_LINE/2 + 1];  
   if (strcmp(cmd, "history") == 0)
       history(hist, current);
   else if (strcmp(cmd, "!!") == 0)
       execMostRecHist(hist, current-1);
   else if (strcmp(cmd, "!%d") == 0)
       num = %d;
   else
       {//do stuff}

I understand this is completely wrong syntax for strcmp(), but just as an example of how I am gathering user input.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Sean
  • 1,283
  • 9
  • 27
  • 43

3 Answers3

1

Don't you like writing a checker by yourself?

#include <ctype.h>
#include <stdio.h>

int check(const char *code) {
    if (code == NULL || code[0] != '!') return 0;
    while(*(++code) != '\0') {
        if (!isdigit(*code)) return 0;
    }
    return 1;
}


/* ... */

if (check(cmd))
    sscanf(cmd + 1, "%d", &num);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

strcmp doesn't know about format specifiers, it just compares two strings. sscanf does what you want: It tests whether a string has a certain format and converts parts of the string to other types.

For example:

int n = 0;

if (sscanf(cmd, " !%d", &num) == 1) {
    // Do stuff; num has already been assigned
}

The format specifier %d tells sscanf to look for a valid decimal integer. The exclamation mark has no special meaning and matches only if there is an exclamation mark. The space at the front means that the command may have leading white space. Nothe that there may be white space after the exclam and before the number and that the number may well be negative.

The format specifier is special to the scanf family and related to, but different from the ´%dformat ofprintf`. Is usually has no meaning in other strings and certainly not when it is found unquoted in the code.

M Oehm
  • 28,726
  • 3
  • 31
  • 42
0

Use sscanf() and check its results.

char cmd[MAX_LINE/2 + 1];  
num = 0;  // Insure `num` has a known value
if (strcmp(cmd, "history") == 0)
   history(hist, current);
else if (strcmp(cmd, "!!") == 0)
   execMostRecHist(hist, current-1);
else if (sscanf(cmd, "!%d", &num) == 1)
   ;
else
   {//do stuff}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256