Ignoring integers that are next to characters with sscanf ()

Sorry for the simple question, but I'm trying to find an elegant way to prevent my program from seeing input like "14asdf" and accept it just like 14.

if (sscanf(sInput, "%d", &iAssignmentMarks[0]) != 0)

Is there an easy way to prevent sscanfintegers from being pulled from garbled strings?

+5
source share
5 answers

You cannot directly stop sscanf()the execution of the fact that it is designed and specified for execution. However, you can use a little-known and rarely used function sscanf()to make it easy to detect that a problem has occurred:

int i;

if (sscanf(sInput, "%d%n", &iAssignmentMarks[0], &i) != 1)
    ...failed to recognize an integer...
else if (!isspace(sInput[i]) && sInput[i] != '\0')
    ...character after integer was not a space character (including newline) or EOS...

%n , , ( ). %n sscanf() C89.

strtol() - ( , , sscanf(), ). , .

+3

. strtol sscanf. strtol endptr , . , endptr , .. *endptr == \0.

char *endptr = NULL;
long n = strtol(sInput, &endptr, 10);
bool isNumber = endptr!=NULL && *endptr==0 && errno==0;

( . . strtol man.

+2

. ++ ! :

char unusedChar;
if (sscanf(sInput, "%d%c", &iAssignmentMarks[0], &unusedChar) == 1)
+2

scanf . strtol . strtol char *, , ; 0, :

char input[SIZE]; // where SIZE is large enough for the expected values plus
                  // a sign, newline character, and 0 terminator
...
if (fgets(input, sizeof input, stdin))
{
  char *chk;
  long val = strtol(input, &chk, 10);
  if (*chk == NULL || !isspace(*chk) && *chk != 0)
  {
    // input wasn't an integer string
  }
}
0

++, .

Check here: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2

If you're interested, yes, it came from another entry. What answers this question: Another answer

0
source

All Articles