views:

18

answers:

1

I want to convert val.ElementAt(i) to float value :

 float *d = new float[NMAX];
 char *buffer = new char[128]; 
 CStringArray val;
 //adding some values to val

 buffer = (LPSTR)(LPCSTR)val.ElementAt(i).GetBuffer();
 d[i] = atof(buffer);

as the result in d[i] I have just part of the value(if it was 55 in d is - 5, 666 - 6 ...), help me please!

+2  A: 

You shouldn't be assigning buffer; it's bad code (doesn't do what you want). You could use strncpy, but instead, why not just use the CString directly:

d[i] = atof(val.ElementAt(i));

Assuming you're compiling for MBCS, this should work.

BTW, you could also use the operator[] overload, to make the code slightly cleaner, eg:

d[i] = atof(val[i]);

Edit: If you're using UNICODE, you need the dynamic MBCS/UNICODE macro version of atof, which is _ttof. See http://msdn.microsoft.com/en-us/library/hc25t012%28v=VS.90%29.aspx for the full reference. So the code becomes:

d[i] = _ttof(var[i]);

Oh, forgot to include (duh): all these functions return a double, which is not necessarily the same thing as float. So change your result array to doubles, or explicitly cast the result of the conversion.

Nick
both of your variants show error error C2664: 'atof' : cannot convert parameter 1 from 'CString' to 'const char *'
Sergey
i am using vs2008
Sergey
d[i] = atof((LPSTR)(LPCSTR)val.ElementAt(i).GetBuffer()); - for this, problem remains too, just part of the value in d[i]
Sergey
Are you compiling with UNICODE? If so, you'll need an additional conversion. CString has an operator for const TCHAR*, which will work for MBCS compilation. I'll amend the answer for the MBCS/UNICODE solution.
Nick