Skip to content

Instantly share code, notes, and snippets.

@rsnemmen
Created July 31, 2017 21:31
Show Gist options
  • Select an option

  • Save rsnemmen/2277d0ad1a171a4a16110b46eab2c75a to your computer and use it in GitHub Desktop.

Select an option

Save rsnemmen/2277d0ad1a171a4a16110b46eab2c75a to your computer and use it in GitHub Desktop.
Breaks down a string containing a list of numbers into a float array. C code.
/*
Breaks down a string containing a list of numbers in a float array.
Recipe copied from here: https://stackoverflow.com/a/1862712/793218
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main() {
char input[] = "1.2 2.3 3.4 4.5 5.6 6.7 7.8";
char *delim = " "; // input separated by spaces
char *token = NULL;
char *unconverted;
double value[7];
int i;
i=0;
for (token = strtok(input, delim); token != NULL; token = strtok(NULL, delim)) {
value[i] = strtod(token, &unconverted);
if (!isspace(*unconverted) && *unconverted != 0) {
/* Input string contains a character that's not valid
in a floating point constant */
exit(1);
}
i++;
}
for (i=0; i<7; i++) {
printf("%f\n", value[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment