Get only prime in C / C ++

I have a function stoi:

static int *stoi(const char *c) {
    int *r = new int[2];
    r[1] = sscanf(c, "%d", &r[0]);
    return r;
}

When I give c = "a5", for example, it does not work.

When I give c = "543336535", it works.

But when I give c = "45sdfff-sdbsdf esg5sq4f", he will return r[0] = 45, and I do not want this, because after 45...

There are some non-digital characters.

I need my read-only function with line number.

+3
source share
2 answers

To minimize the code you already have, you can use the function %n sscanf:

int chars_read;
r[1] = sscanf(c, "%d%n", &r[0], &chars_read);

If it is chars_readless than the length of the string, then it sscanfdid not consume all the characters, so the string did not consist entirely of one whole.

Linux scanf , , 1 , . sscanf, :

switch (r[1]) {
  case EOF: // empty string
    break;
  case 0: // doesn't start with numeric characters
    break;
  case 1: // starts with number; sscanf follows standards
  case 2: // starts with number; sscanf follows TC1
    if (c[chars_read] == '\0')
      r[1] = 1; // we read entire string
    else
      r[1] = 0; // didn't read entire string; pretend we read nothing
    break;
  default: // shouldn't happen
    assert(FALSE);
}
+5

C, strtol, , . , . , - , .

++, , , Boost lexical_cast, , , , - .

+3

All Articles