2017-08-12 50 views
2

所以香港专业教育学院写了一个小程序这样sscanf的不是从字符串中的元素扫描正常

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
#include <string.h> 

const double PI = 3.14159; 

int main() 
{ 
    char str[120]; 
    double distance, azimuth; 
    double delta_x = 0; 
    double delta_y = 0; 

    FILE *fp = fopen("input.txt", "r"); 
    if (fp == NULL) 
     return -1; 
    fgets(str, sizeof(str), fp); //skip first line 

    while (fgets(str, sizeof(str), fp)) { 
     if (strcmp("Dig here!", str) == 0) 
      break; 
     printf(str); 
     sscanf(str, "go %f feet by azimuth %f\n", &distance, &azimuth); 
     printf("distance %f azimuth %f\n", distance, azimuth); 
     delta_y += distance * sin(azimuth * (PI/180)); 
     delta_x += distance * cos(azimuth * (PI/180)); 
    } 

    printf("%d %d", delta_x, delta_y); 

    fclose(fp); 
    return 0; 
} 

input.txt中看起来像这样

Stand at the pole with the plaque START 

go 500 feet by azimuth 296 

go 460 feet by azimuth 11 

Dig here! 

但是输出给

go 500 feet by azimuth 296 

distance 0.000000 azimuth 0.000000 

我敢肯定,这是一个愚蠢的错误,我失踪,但我似乎无法找到它,任何帮助,将不胜感激。

+4

使用'%lf'代替'%F'为'sscanf'中的'double'。 – BLUEPIXY

+0

@BLUEPIXY修复它谢谢!你介意告诉我为什么这是有效的吗? – Mitchel0022

+0

阅读[sscanf](http://en.cppreference。com/w/c/io/fscanf) – BLUEPIXY

回答

3

scanf"%f"格式说明为float类型:

˚F –匹配任选签署浮点数;下一个指针必须是指向float的指针。

如果要解析double类型,然后结合使用的l格式说明与f

–表示要么转换将是di中的一个,o,u,x,X,或Ñ和下一指针是指向一个long intunsigned long int(而不是int),或者转换将是Ë之一,˚F,或和下一指针是指向double(而不是float)的指针。

所以,你应该改变你的格式字符串如下:如果一个换行符被读取

sscanf(str, "go %lf feet by azimuth %lf\n", &distance, &azimuth); 
printf("distance %lf azimuth %lf\n", distance, azimuth); 

注意fgets可能包含尾随'\n',换句话说,它被保存到缓冲区。因此,在比较fgets"Dig here!"之间的输入之前,必须先删除换行符。

有许多选项要做到这一点,在评论下面你可以看到一个很好的一个,或者你可以用下面的办法与strcspn功能:

str[strcspn(str, "\r\n")] = '\0'; /* works for any combination of CR and LF */ 

if(strcmp("Dig here!", str) == 0) 
    break; 
+2

另外请注意'if(strcmp(“Dig here!”,str)== 0)'由于尾随的换行符不太可能匹配。 – chqrlie

+0

@chqrlie,谢谢你的建议,我相应地编辑了我的答案。 – Akira

+2

不保证最后一行将包含*行尾*。更好'len = strlen(str);如果(len && str [len-1] ==''n')str [ - len] = 0;'然后比较if(strcmp(“Dig here!”,str)== 0)'。 –