2013-10-12 118 views
0

我一直有一些问题,下面这段代码...字符串转换为浮动动态

代码的主要思想是按行读入线和转换字符字符串转换为浮动并保存彩车在名为nfloat的数组中。

的输入是包含此一.txtÑ =串的数量,在这种情况下Ñ = 3

3 
[9.3,1.2,87.9] 
[1.0,1.0] 
[0.0,0.0,1.0] 

的第一个数字,3是载体的,因为我们可以看到数在图像中,但该数字不是静态的,输入可以是57等,而不是3

到目前为止,我已经开始做了以下(仅1载体的情况下),但代码中有一些内存错误,我认为:

int main(){ 
    int n; //number of string, comes in the input 
    scanf("%d\n", &n); 
    char *line = NULL; 
    size_t len = 0; 
    ssize_t read; 
    read = getline(&line,&len,stdin); //here the program assigns memory for the 1st string 
    int numsvector = NumsVector(line, read);//calculate the amount of numbers in the strng 
    float nfloat[numsvector]; 
    int i; 
    for (i = 0; i < numsvector; ++i) 
    { 
     if(numsvector == 1){ 
      sscanf(line, "[%f]", &nfloat[i]); 
     } 
     else if(numsvector == 2){ 
      if(i == 0) { 
       sscanf(line, "[%f,", &nfloat[i]); 
       printf("%f ", nfloat[i]); 
      } 
      else if(i == (numsvector-1)){ 
       sscanf((line+1), "%f]", &nfloat[i]); 
       printf("%f\n", nfloat[i]); 
      } 
     } 
    else { //Here is where I think the problems are 
     if(i == 0) { 
      sscanf(line, "[%f,", &nfloat[i]); 
      printf("%f\n", nfloat[i]); 

     } 
     else if(i == (numsvector-1)) { 
      sscanf((line+1+(4*i)), "%f]", &nfloat[i]); 
      printf("%f\n", nfloat[i]); 
     } 
     else { 
      sscanf((line+1+(4*i)), "%f,", &nfloat[i]); 
      printf("%f\n", nfloat[i]); 
     } 
    } 
} 

好了,问题来与sscanf说明,我认为在两个浮筒或一个字符串的情况下,代码工作正常,但在3个或多个浮标的情况下,代码不能很好地工作,我不明白为什么...

这里我附加功能,但它似乎是正确的...问题的重点仍然是主要的。

int NumsVector(char *linea, ssize_t size){ 
     int numsvector = 1; //minimum value = 1 
     int n; 
     for(n = 2; n<= size; n++){ 
      if (linea[n] != '[' && linea[n] != ']'){ 
       if(linea[n] == 44){ 
        numsvector = numsvector + 1; 
       } 
      } 
     } 
     return numsvector; 
} 

请有人帮助我了解问题出在哪里?

+1

看不到任何证明计算'(line + 1 +(4 * i))'的东西。它假设你的浮动长度是三个字符,但即使在你提供的数据中也不是这样。我认为这种方法是错误的,需要某种标记化,甚至可能使用strtok。 – john

+0

是的,我认为同样的事情,但我只能用sscanf的:( – Gera

+2

我看不到相关[标签:C++]任何声明。在你的代码中删除标签或选择其中一个 –

回答

0

好 - 如果您更换当前与这个循环中,你nfloat数组应该在它的正确的数字结束。

/* Replaces the end ] with a , */ 
line[strlen(line) - 1] = ','; 

/* creates a new pointer, pointing after the first [ in the original string */ 
char *p = line + 1; 
do 
{ 
    /* grabs up to the next comma as a float */ 
    sscanf(p, "%f,", &nfloat[i]); 
    /* prints the float it's just grabbed to 2 dp */ 
    printf("%.2f\n",nfloat[i]); 
    /* moves pointer forward to next comma */ 
    while (*(p++) != ','); 
} 
while (++i < numsvector); /* stops when you've got the expected number */ 
+0

太棒了!它的作品:D!但它打印了一些垃圾,例如在输入中我们可以看到:[9.3,1.2,87.9],但是做一些printf我们可以看到: [9.300000,1.200000,87。900002] – Gera

+1

@Gerard通常情况下,您可以通过投票向上/接受他们的回答 –

+0

我想你看到一个浮点精度误差感谢有人在计算器。没有什么可以做的,除了只使用2个d.p.因为无论如何,数据看起来都是这样的。我已经更新了上面的答案,包括2个d.p. printf语句。 – Baldrick