sscanf的C中分离数量不明的双打一行到一个数组 [英] sscanf in C. Separating unknown number of doubles on a line to an array

查看:138
本文介绍了sscanf的C中分离数量不明的双打一行到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也有类似的问题在那里,但没有这并真正帮助我与我的问题。
我得到数目不详的浮点数的字符串,我不得不削减seperatly他们到一个数组中。

I there are similar questions out there, but none of that did really help me with my problem. I get a string with unknown number of floating point numbers and I have to cut them seperatly to an array.

我所得到的是:

   h=0;
   while(fstring[h]!='\n'){  //So first I count how many spaces there are in the string
            if(fstring[h]==' '){
                sc++;
            }
            h++;
    }
    vars=sc;
    for(h=0;h<vars;h++){
        sscanf(fstring,"%lf",&scanned);
        matrix[h]=scanned;
    }

那么,为什么这不是工作?它抛出一个错误每次..

So why does this not work? It throws an error every time..

推荐答案

您可以做这样的事情,而不是:

You could do something like this instead:

#include <stdio.h>

int main ()
{
    double fmatrix[100] = { 0 };
    double *matrix = fmatrix;
    double scanned;
    int bytesread;
    char string[100];
    char *fstring = string;
    int i;

    fgets ( string, 99, stdin );
    fstring = string;

    while ( sscanf ( fstring, "%lf%n", &scanned, &bytesread ) > 0 )
    {
        fstring += bytesread;
        *matrix++ = scanned;
    }

    matrix = fmatrix;

    for ( i = 0; i < 50; i++ )
    {
        printf ( "%lf\n", *matrix++ );
    }
}

这篇关于sscanf的C中分离数量不明的双打一行到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆