1

I have a string which contains hundreds of double values separated by spaces, and I need to read them into an array.

Obviously, using sscanf("%lf %lf .... ",array[0], array[1],...) is not a sane option. I could save this string to a file and use fscanf since the "head" moves forward when reading from a file. I want to know if there another way to do this.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    look at strtok function – OldProgrammer Jul 24 '19 at 15:17
  • The proper solution is to use `strtod` making use of `endptr` parameter to step through the string retrieving doubles as you go. There are probably 50 examples on this site. You can also use `strtok` to tokenize the string, see [How to extract numbers from string and save them into its own buffer?](https://stackoverflow.com/questions/47536394/how-to-extract-numbers-from-string-and-save-them-into-its-own-buffer/47543933?r=SearchResults&s=4|26.8547#47543933). – David C. Rankin Jul 24 '19 at 15:19
  • can you add your input and expected output? – GOVIND DIXIT Jul 24 '19 at 15:20

2 Answers2

1

You can use for example the following approach.

#include <stdio.h>

int main( void ) 
{
    const char *s = " 123.321 456.654 789.987";
    enum { N = 10 };
    double a[N] = { 0.0 };

    int pos = 0;
    size_t n = 0;
    while ( n < N && sscanf( s += pos, "%lf%n", a + n, &pos ) == 1 ) n++;

    for ( size_t i = 0; i < n; i++ ) printf( "%.3f ", a[i] );
    putchar( '\n' );
}

The program output is

123.321 456.654 789.987

Or you can introduce an intermediate pointer of the type const char * if you need to keep the original address of the string in the variable s.

For example

#include <stdio.h>

int main( void ) 
{
    const char *s = " 123.321 456.654 789.987";
    enum { N = 10 };
    double a[N] = { 0.0 };

    int pos = 0;
    size_t n = 0;
    const char *p = s;
    while ( n < N && sscanf( p += pos, "%lf%n", a + n, &pos ) == 1 ) n++;

    for ( size_t i = 0; i < n; i++ ) printf( "%.3f ", a[i] );
    putchar( '\n' );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-3

You can use split function of String Class. Lets say your string is presents in 's'. Then you can do something like this -> String[] str=s.split('\\s'); this will break string based on whitespaces and generate arrays of String.Now you have to convert this into double value so you can iterate through String array and convert into doble and store it in separate array like this->

for(String st: str)
{
  var=Double.parseDouble(st);
}

'var' could be array or variable where you want to store it. Hope it helps.

Aviii04
  • 21
  • 1
  • 5