【问题标题】:How do I fscanf without knowing the float length?我如何在不知道浮点长度的情况下进行 fscanf ?
【发布时间】:2013-11-28 16:05:01
【问题描述】:

我想扫描数据文件中的“G1”,然后是 X、Y 和 Z 坐标,以浮点数给出,但坐标用不同的小数位数表示。文件中的三行可能如下所示,其中第一行和第三行包含坐标:

    G1X59.7421875Y60.2578125
    M101S3F12
    G1X50.25

有人知道如何fscanf 一个具有如此不可预测性质的浮点数吗? 当我查看结果(printf()'s)时,数字与文件不匹配。我希望 fscanf 扫描“通过”短浮动,因为它们没有被打印出来。

我的遍历代码:注意对find_arg()的函数调用,我认为问题出在哪里。

char line[LINE_LENGHT];
int G1, X, Y, Z, F, junk= 0;
float fdx, fdy, fdz;

while(!feof(file_gcode)){
   for (i = 0; i < LINE_LENGHT; i++){
      fscanf(file_gcode, "%c", &line[i]);
      if ((line[i-1] == 'G')&&(line[i] == '1')) {
         G1 ++;
         while (line[i] != '\n'){
            if( (line[i] == 'X') || (line[i]==('Y')) || (line[i]==('Z')) || (line[i] == ('F')) ) {
               find_arg(line[i]);
            }
            i ++;
            fscanf(file_gcode, "%c", &line[i]);
         }
         printf("X = %f, Y = %f, Z = %f \n", fdx, fdy, fdz);
      }
   }
}
printf("-------------------\n");
printf("G1's : %i\n", G1);
printf("X's : %i\n", X);
printf("Y's : %i\n", Y);
printf("Z's : %i\n", Z);
printf("F's : %i\n", F);
printf("other's : %i\n", junk);
printf("-------------------\n");
}

int find_arg(char c){
   if (c == 'X'){
      X ++;
      fscanf(file_gcode, "%f", &fdx);
   }
   else if(c == 'Y'){
      Y ++;
      fscanf(file_gcode, "%f", &fdy);
   }
   else if(c == 'Z'){
      Z ++;
      fscanf(file_gcode, "%f", &fdz);
   }
   else if(c == 'F'){
      F ++;
   }
   else junk ++;
}

【问题讨论】:

    标签: c++ c decimal scanf


    【解决方案1】:
    float x, y, z;
    int nread;
    nread = fscanf(fp, "G1X%fY%fZ%f", &x, &y, &z);
    

    nread 将是扫描的坐标数。因此,如果该行只有 XY 它将是 2。

    【讨论】:

      【解决方案2】:

      您可以使用strtok 来解析输入行 - 这会拆分出您关心的字符串位。它消除了对字符串格式的一些依赖 - 但如果您的字符串格式众所周知,@Barmar 的解决方案应该可以正常工作。

      这样的事情可能是一个可行的选择:

      nextLine = fgets(fp);
      // check line has "G1" in it:
      if(strstr(nextLine, "G1)!=NULL) {
      // look for 'X':
        strtok(nextLine, "X");
      // find the thing between 'X' and 'Y':
        xString = strtok(NULL, "Y");
        if(xString != NULL) sscanf(xString, "%f", &xCoordinate);
      // find the thing to the end of the line:
        yString = strtok(NULL, "\n");
        if(yString != NULL) sscanf(yString, "%f", &yCoordinate);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多