LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to convert characters with notations into double (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-convert-characters-with-notations-into-double-702311/)

Jane2008 02-04-2009 02:01 PM

How to convert characters with notations into double
 
#include <stdio.h>
#include <string.h>

void rd_vconfig()
{
int index=0;
int i, j=0;
int length = strlen(strtemp);
printf("The length of the temperature string is %d\n", length);
char *str1;
double temp[8];
char *strtemp = "+13.56+3.184+5.295+4.775+12.633+11.44-11.74-12.996";

for(i=0; i<length; i++)
{
if((i != 0) && (strtemp[i] == '+' || strtemp[i] == '-'))
{
str1[j] = '\0';
printf("%s\n", str1);
temp[index] = atof(str1);
index++;
j=0;
}
str1[j] = strtemp[i];
j++;

}
// for(i=0; i<index; i++)
// printf("%d\t", temp[i]);
}
It seems that the last number -12.996 doesn't display.
I don't know why. And the atof() function doesn't work.
Could anyone help me?
Thanks.

theNbomr 02-04-2009 03:13 PM

Several things bad here. For starters, when posting source code, please use [CODE] tags to preserve formatting and prevent whitespace folding.
Next, you have used str1 as an array, but declared it as a pointer to char. If you are going to store something at the place that str1 points, then str1 should have been initialized to point at some writeable memory (try malloc), or should be defined as an array.
You convert strings to doubles with atof(), but then try to print them as integers.
Your loop terminates at the end of the literal string, but you only do a conversion to floating point when you find a '+' or '-'. This would explain your 'last number' question.
I assume that after all these years, someone else would have noticed if atof() really didn't work, so it is probably your expectation of what it should do that is incorrect. What exactly do you mean by "doesn't work"?
Since you seem to know a priori that your string contains exactly 8 numbers, perhaps it would be easier to use sscanf() to do your conversions. This would reduce your conversion code to one line:
Code:

    sscanf( strtemp, "%lf%lf%lf%lf%lf%lf%lf%lf", &temp[0],&temp[1],&temp[2],&temp[3],&temp[4],&temp[5],&temp[6],&temp[7] );
--- rod.


All times are GMT -5. The time now is 02:23 AM.