从字符串中读取数字数组

时间:2019-07-24 15:14:00

标签: c split scanf c-strings

我有一个包含数百个用空格分隔的双精度值的字符串,我需要将它们读入数组。

很明显,使用sscanf("%lf %lf .... ",array[0], array[1],...)不是明智的选择。我可以将字符串保存到文件中并使用fscanf,因为从文件中读取时,“ head”会向前移动。我想知道是否还有另一种方法。

2 个答案:

答案 0 :(得分:1)

例如,您可以使用以下方法。

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

程序输出为

123.321 456.654 789.987

或者,如果需要将字符串的原始地址保留在变量const char *中,则可以引入类型s的中间指针。

例如

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

答案 1 :(得分:-3)

您可以使用String Class的split函数。 假设您的字符串以“ s”表示。然后,您可以执行以下操作-> String[] str=s.split('\\s');,这将基于空白打破字符串并生成String数组。现在,您必须将其转换为double值,以便可以遍历String数组并转换为doble并存储它在这样的单独数组中->

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

'var'可以是要存储它的数组或变量。 希望对您有所帮助。