ATK
ATK

Reputation: 1526

Identify numbers in mixed formats within a string in C

I have the following string:

 char *line; 
 char temp_line;

After some processing my pointer line pointing to temp_line contains the following string:

 "H2 + CH = CO2      4.00e-003     3.00e10     43.00"

I need a routine which can identify the three numbers you see. I can always assume there will be three different numbers. But I cannot assume that all three numbers are given in exponential form.

What is the best way to achieve this in C?

Is there a way to let C read the line reversely, and instruct it to extract the last three figures of that line?

Upvotes: 0

Views: 40

Answers (1)

chux
chux

Reputation: 154065

Is there a way to let C read the line reversely, and instruct it to extract the last three figures of that line?

Sure, parse the string and save last 3 successful conversions.
The below does consume s.

// Return parse count;
int read_last_3_double(char *s, double y[3]) {
  const char *delimiters = " \n\t";
  int i = 0;
  char *token = strtok(s, delimiters);
  while (token) {
    char *endptr;
    double x = strtod(token, &endptr);
    // If no conversion or fails to end with a null character. 
    if (token == endptr || *endptr) {
      // No conversion
      i = 0;
    } else {
      if (i == 3) {
        y[0] = y[1];
        y[1] = y[2];
        y[2] = x;
      } else {
        y[i++] = x;
      }
    }
    token = strtok(NULL, delimiters);
  } // endwhile
  return i;
}

Upvotes: 1

Related Questions