0

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.

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

IMO, this is the best proposed solution. The other solutions all use “evil” functions that modify their arguments or maintain internal state.
this clearly looks like the easiest solution and it's exactly what i wanted. i argued a bit with it because i didn't realize where the endpointer should come from, but alas i made it work. thank you.
1

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

Comments

0

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

Comments

-1

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.

3 Comments

You left out an 's' on sscanf() in your example.
This doesn't say anything about how to skip the beginning of string to get to the next number.
@unwind ya right. now i have specified how to get the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.