简体   繁体   中英

Reading an array of numbers from a string

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.

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' );
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM