我创建了以下程序
#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
我肯定这是一个愚蠢的错误,我错过了,但我似乎找不到它,任何帮助都将不胜感激。
发布于 2017-08-12 07:27:44
"%f"
格式说明符scanf
用于float
类型:
f -匹配可选签名的浮点数;下一个指针必须是指向
float
的指针。
如果希望解析double
类型,则使用l
格式说明符和f
组合使用。
< l >指示转换为d、i、o、u
E 223>、E 124x>、<>E 126
XE 227>,或<>E 128nE 229E 229>,下一个是指向D 30或d31的指针(而不是d32>),或者是E 133e代码><<代码><代码><代码>>代码<<><<>代码>指针>>指针><><<>代码>指针>>指针><<>>指针>
>指针><>代码><<><>指针<><<><>代码><<>代码><<>>指针><>代码>指针<><<>代码>指针<<>代码>指针><<>代码><>代码><<>代码><>代码>指针><代码>(而不是d32>),或者转换为E 133e代码><代码>代码><<>>代码><<><><<><>代码><><<><<>代码><<><<>
因此,您应该按照以下方式更改您的格式字符串:
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;
https://stackoverflow.com/questions/45645788
复制相似问题