简体   繁体   中英

convert string of ints and floats to a float array in C

what I'm trying to do is to send a string over the network. the point is that the server which receives the string must make the sum of all the numbers and send it back. so i think the easiest way is to take the string and put it in a float array (it does not matter if ints get in there aswell, since the final sum will be a float number).

unfortunately i have no idea how to do that, or more exactly, how to approach it. how do i take the numbers 1 by 1 from a string (let's say, each number is separated by a space)? there must be some function but i can't find it.

the language is plain C under unix.

Use strtod() to convert the first number in the string to double . Add that to your sum, then use the endptr return value argument to figure out if you need to convert another, and if so from where. Iterate until the entire string has been processed.

The prototype for strtod() is:

double strtod(const char *nptr, char **endptr);

Also note that you can run into precision issues when treating integers as floating-point.

您可以使用fscanf从流中读取,就像使用scanf从stdin中读取一样。

You can use strtok to split your string and atof to convert it to float.

char* p;
float farr[100];
int i = 0;
//str is your incoming string
p = strtok(str," ");
while (p != NULL)
{
    farr[i] = atof(p);
    p = strtok(NULL, " ");
}

I just ran it in an online compiler - http://ideone.com/b3PNTr

you can use sscanf() to read the formatted input from a string.
you can use something like

string=strtok(input," ")
while(string!=NULL)
{ sscanf(string,"%f",&a[i]);
  i++;
string=strtok(NULL," ");
}

inside a loop. you can use even atof() instead of using sscanf() with %f.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM