Reading C character arrays into doubles
This is a very elementary question, but my C is very very rusty and I need a refresher. I have a string which is always in exactly the same format: di ###.# ###.# ###
.
I would like to read the first number into d1
, the second into d2
, and the third into d3
.
int main ()
{
double d1, d2, d3;
char mystring[] =开发者_如何学Python "di 123.4 567.8 901";
//some code that I don't know
return 0;
}
Can you guys help me out? I understand strtod() can help just parsing the numbers, but how do I skip over the "di" at the beginning?
You can use sscanf
:
sscanf(mystring, "di %lf %lf %lf", &d1, &d2, &d3);
In this line, you are giving a format string (basically laying out where you expect the numbers to be), and then supplying the addresses of the variables you want the results to be put in, in order. The &
operator takes the address of whatever it is applied to, which in this case is your d1
,d2
, andd3
variables.
(The reference supplied is on a C++ site, but is for this function)
精彩评论