I'm having a very specific problem and haven't found a solution elsewhere. I'm working on a small project and i want to make it more robust by allowing users to input prices with both a comma or dot. So i made a little function that allows me to do that:
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main () {
setlocale(LC_ALL, "Portuguese");
float val;
char str[20];
scanf("%s", str);
for (int i = 0; str[i] != '\0'; ++i)
if (str[i] == ',')
str[i] = '.';
val = atof(str);
printf("String value = %s, Float value = %f\n", str, val);
return(0);
}
This would work as intended, were I not Portuguese. Since we mostly use a comma in decimal numbers, using the atof
function doesn't work because it converts to floats with a dot, and then when I try to printf
the float it will show 0.0 but if you delete the line setlocale(LC_ALL, "Portuguese");
it will work just fine. Any ideas?