2013-11-28 32 views
1

我想扫描数据文件中的“G1”,然后在浮点数中给出X,Y和Z坐标,但坐标用不同的小数位数表示。三线文件可能看起来像,其中第一和第三包含坐标:如何在不知道浮子长度的情况下fscanf?

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 ++; 
} 

回答

1
float x, y, z; 
int nread; 
nread = fscanf(fp, "G1X%fY%fZ%f", &x, &y, &z); 

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

+0

我想,这大概比我的解决方案更强大的... – Floris

0

您可以使用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); 
} 
相关问题