icarus
icarus

Reputation: 166

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.

Upvotes: 0

Views: 1264

Answers (4)

unwind
unwind

Reputation: 399843

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.

Upvotes: 4

LearningC
LearningC

Reputation: 3162

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.

Upvotes: -1

Arjun Sreedharan
Arjun Sreedharan

Reputation: 11453

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

Upvotes: 0

radomaj
radomaj

Reputation: 871

You can use fscanf to read from a stream, just like you would use scanf to read from stdin.

Upvotes: 1

Related Questions