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.

3
  • 1
    look at strtok function Commented Jul 24, 2019 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?. Commented Jul 24, 2019 at 15:19
  • can you add your input and expected output? Commented Jul 24, 2019 at 15:20

2 Answers 2

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' );
}
Sign up to request clarification or add additional context in comments.

Comments

-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.

1 Comment

The question is about C as seen by the tags

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.