I’ve wrote a program that gets a string, and then calculate a total value of the string togheder…
For Example :
char data[256] = "1$0.83331333333333334$false$false"; // the data
Here I need to do the calculation of 1 + 0.83331333333333334
so this is what I wrote:
char data[256] = "1$0.83331333333333334$false$false"; // the data
double grade = 0;
int i = 0;
int times = 0;
char temp[256] = "";
int flag = 0;
while (flag == 0)
{
times = 0;
if (isdigit(data[i])) // if it's a number
{
if (data[i + 1] == '.') // if it's a double number
{
i = i + 2;
while (isdigit(data[i])) // putting it into a temp array
{
temp[i] = data[i];
i++;
times++;
}
grade = grade + (double)temp / (times * 10);
}
grade = grade + (int)data[i]; // if it's an int number, putting it into grade right away
}
if (data[i] == '\0')
{
flag = 1;
}
i++;
}
printf ("%f\n", grade);
the problem is in the line :
grade = grade + (double)temp / (times * 10);
it says “pointer value used where a floating point value was expected”.
I really couldent understand whats the problem…
Thanks 🙂
Edit:
Thanks for your help!
I’ve been able to convert the number into a string..
so for example, now if I have the big string in data, with couple of doubles inside it, I can take in a loop every time the double into a new string.
I’ve used atof to convert it into a double, though it seems that the double is too small..
For example :
I have in the string temp : “83331333333333334”, and I used atof on it -> the new double has 8333313 only… the rest is like not going into the double..
I guess that the number is too big for a double number… so what Can I do ?
Thanks!
You cannot simply cast a
chararray todoubleand expect the compiler to treat it as adouble. You need to converttempvia a suitable function such asstrtodand then use that value in your calculations.Note that
strodrequires a C-style string i.e. null-terminated character array. So, passing intempis not enough. You need to null terminatetempi.e. once you are done inserting the digits, add antemp[ i ] = 0;.Here’s a little program that will probably help you fix your errors and help you use
strtod:Since the OP wanted something simpler than
strtod:You can use
double atof(const char *nptr);. In my sample source replace thestrtod( p, NULL );byatof( p );and that should get you started. The problem withatofand friends is that error handling is difficult and if the value cannot be represented you silently invoke undefined behavior.