【发布时间】:2015-01-09 14:27:26
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct vector
{
double x;
double y;
double z;
};
struct vector *array;
double length(struct vector*);
int main()
{
int num,i;
double xin;
double yin;
double zin;
char buffer[30];
char buffer2[30];
printf("Enter number of vectors:");
fgets(buffer, 30, stdin);
sscanf(buffer, "%d", &num);
array = malloc( sizeof(struct vector) * num);
for(i=0;i<=num;i++)
{
printf("Please enter x y z for the vector:");
fgets(buffer2,100,stdin);
sscanf(buffer2, " %lf %lf %lf", &xin, &yin, &zin);
array[i].x = xin;
array[i].y = yin;
array[i].z = zin;
}
for(i=0;i<=num;i++)
{
printf( "Vector:%lf %lf %lf has a length of %lf\n", array[i].x, array[i].y, array[i].z, length(&array[i]));
}
}
double length(struct vector* vec)
{
return sqrt( (vec->x * vec->x) + (vec->y * vec->y) + (vec->z * vec->z) );
}
好的,上面的代码差不多完成了,它询问用户向量的数量,然后它询问用户这些向量的值,然后它会计算长度并相应地打印出来。
我试图在这里检查一些错误,但我似乎无法得到它...我查找了 fgets 和 sscanf 的所有可能返回值,但我似乎无法得到它
防御功能
FIRST printf-----input 只能是大于 0 的单个数字,EOF 应该返回类似 printf("enter a number--bye!") 的消息,所以我尝试了
while( sscanf(buffer, "%d", &num) ==1 && num > 0 )
但如果输入 3dadswerudsad 之类的内容,它仍然有效
此外,当用户输入向量的 3 个值时,如果为向量输入了除 3 个双精度之外的任何值,则程序应该以一条消息终止,所以我尝试了
while( sscanf(buffer2, "%lf %lf %lf", &xin, &yin, &zin) ==3 )
但它不会检查这些不正确的输入!!
我要疯了
【问题讨论】:
-
您的 sscanf 正在按预期工作。您已经告诉它扫描 %d - 任何十进制数。由于输入的字符串以
3开头,sscanf 会发现 3...另外,您的长整数 sscanf 在模式的开头有一个空格... -
如果当前行不是有效输入,您应该读取一个新行,可能在
while循环中。 -
所以没有办法绕过以数字开头的线路?
-
您始终可以采用两步方法:使用
%s而不是数字扫描字符串,然后通过使用strtol测试该字符串来验证它是否是有效数字。 (strtol为您提供了指向已解析数字之后的最后一个字符的指针,对于有效数字,该指针应为'\0'。) -
0)
i<=num-->i<num,char buffer2[30];-->char buffer2[100];
标签: c data-structures error-handling structure