-
Changing decimal point
Hey ppl. I am currently doing some coursework at uni and would like some help on the locale.h.
I am reading a line of a csv file into a buffer and then putting each number into a member of a structure. The thing is the numbers are using a comma's as the decimal point instead of a dot. Can someone tell me how i would use the locale.h to change how the decimal point is read.
thanx
-
maybe this might help?? The simplest solution would be to read the line into a buffer then replace all the commas with a period.
-
There is other ways to do it but I have been told to try and use the locale.h.
anyway i found this code which tells me what the decimal point is :
Code:
#include<stdio.h>
#include<locale.h>
int main()
{
struct lconv *ptr;
char *decimal;
setlocale(LC_ALL, "");
ptr = localeconv();
decimal = ptr->decimal_point;
}
I fully understand this code but I cant figure out how to change the locale. Can someone please tell me the code to replace the decimal point?
thanx
-
replacing the comma with a decimal point is pretty trivel. What is the field separator in that file -- probably tabs since commas are used in the numbers?
Code:
char *p;
FILE *fp = fopen("somefile.cvs","r");
char iobuf[255]; // or some other bigger or smaller number
while( fgets(iobuf,sizeof(iobuf),fp) )
{
while( (p = strchr(iobuf,',')) != 0)
*p = '.';
// now break the line into its individual fields assumed to be floating-pointer
// integers separated by tabs
p = strtok(buffer,"\t");
while(p)
{
float a = atof(p);
// put a into whatever struct you want it.
p = strtok(0,"\t");
}
}
-
I found that setting local to German will work. But you will want to change it back when done.
Code:
#include<stdio.h>
#include<locale.h>
#include <string.h>
#include <math.h>
void rdfile()
{
float a;
FILE *fp = fopen("somefile.cvs","r");
if(fp == 0)
return;
while( fscanf(fp,"%f",&a) > 0)
{
printf("%f\n",a);
}
fclose(fp);
}
int main()
{
struct lconv *ptr;
char *decimal;
setlocale(LC_ALL, "German");
ptr = localeconv();
decimal = ptr->decimal_point;
rdfile();
return 0;
}
[edit]it appears setlocal() does not affect system-wide local setting -- only the currently running program instance. so there is really no need to set it back to original value unless you need it reset for some other reason. [/edit]
-
thanx for the help. I will just change the country to german.
-
Can you tell me where I can find a list of locals and the details of each one?
-
I have no idea. you might read some of the links thatgoogle produces.