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.

You can use fscanf to read from a stream, just like you would use scanf to read from 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 -

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

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

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

Need Your Help

Scrollview only Works in Listview

android xml listview scrollview

I have the following layout defined in my app:

can not install mvn 3.3.3 on ubuntu 14.04

maven ubuntu

I am using Ubuntu 14.04. I need to run mvn 3.3.3. Currently, the installed mvn version 3.0.5. When I enter