Two problems. It makes your program dependent on the user having that locale on their system. Also, using something like sscanf("%f",...) or strtod will allow a value without a fractional part (which seems to be against your directions) as well as forms like 1,2e3.
Code:
#include <stdio.h>
#include <string.h>
#include <locale.h>
int main() {
if (!setlocale(LC_NUMERIC, "en_DK.utf8")) {
printf("setlocale failed\n");
return 1;
}
char line[1000];
const char *const Seps = " \t\r\n";
while (fgets(line, sizeof line, stdin)) {
char *tok = strtok(line, Seps);
while (tok) {
double f;
int n;
if (sscanf(tok, "%lf%n", &f, &n) == 1 && !tok[n])
printf("%f\n", f);
tok = strtok(NULL, Seps);
}
}
return 0;
}
EDIT: The second problem can be solved with an additional test.
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <locale.h>
int okay(const char *s) {
int commas = 0;
for (const char *p = s; *p; ++p)
if (*p == ',') {
// error if more than 1 comma or it's first or last char
if (++commas > 1 || p == s || !p[1])
return 0;
}
else if (!isdigit(*p))
return 0;
return 1;
}
int main() {
if (!setlocale(LC_NUMERIC, "en_DK.utf8")) {
printf("setlocale failed\n");
return 1;
}
char line[1000];
const char *const Seps = " \t\r\n";
while (fgets(line, sizeof line, stdin)) {
char *tok = strtok(line, Seps);
while (tok) {
double f;
if (okay(tok) && sscanf(tok, "%lf", &f) == 1)
printf("%f\n", f);
tok = strtok(NULL, Seps);
}
}
return 0;
}