开发者

Reading C character arrays into doubles

开发者 https://www.devze.com 2023-02-21 02:45 出处:网络
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 ###.# ###.# ###.

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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号