i have a string in C which i got from some algorithm. it has numeric values in a format like this
0.100
0.840
0.030
0.460
0.760
-0.090
and so on
in need to store each of these numeric values into a float array for numeric processing. i am new to C and found string handling in C to be complex. can anyone tell me how i might implement this.
Are all the values in a single string, like “0.100 0.840 0.030 …”, or do you have a bunch of separate strings, like “0.100”, “0.840”, “0.030”, etc.? If they’re in a single string, are they separated by whitespace (tabs, spaces, newlines) or by printing characters (comma, semicolon)? Do you know how many values you have ahead of time (i.e., how big your float array needs to be)?
To convert a string representing a single floating point value to double, use
strtod()as follows:Read up on
strtod()for details.unconvertedwill point to the first character in the string that wasn’t converted bystrtod(); if it isn’t whitespace or 0, then your string isn’t properly formatted for a floating point value and should be rejected.If all the values are in a single string, you’re going to have to break the string into distinct tokens. The easy (if somewhat unsafe) way to do this is to use
strtok():Read up on
strtok()for details.If you don’t know how many values you have up front, you’ll need to do some memory management. You can dynamically allocate an array of float of some initial size using
malloc()orrealloc(), and then extend it periodically usingrealloc():Don’t forget to
free()array when you’re done with it.