dLiGHT
dLiGHT

Reputation: 147

How to extract a negative number from a string

I need help extracting numbers from a char. Lets say I have:

char str = "   ( 1   22  -4)";

I need to extract each integer and call another method.

while (*p) {
     if (isdigit(*p)) {
         int val = strtol(p, &p, 10);
         on_int(val);
     } else {
         p++;
     }
 }  

I have extracted the integers successfully but I cannot figure out how to extract negatives.

With this code I have extracted 1, 22, and 4. How do I get that negative infront of the 4?

Upvotes: 2

Views: 1918

Answers (2)

qPCR4vir
qPCR4vir

Reputation: 3571

  while (*p) {
       if (isdigit(*p) || ( (*p == '-' || *p == '+')  && isdigit(*(p+1)) )) {
           int val = strtol(p, &p, 10);
           on_int(val);
       } else {
           p++;
       }
   }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

You should change the condition to accommodate the minus, like this:

if ((p[0] == '-' && isdigit(p[1]))|| isdigit(p[0])) ...

Upvotes: 2

Related Questions