c - 如何处理用户输入错误

标签 c data-structures error-handling structure

#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) );
}

好的,上面的代码差不多完成了,它询问用户 vector 的数量,然后它询问用户这些 vector 的值,然后它会计算长度并相应地打印出来。

我试图在这里进行一些错误检查,但我似乎无法得到它...我查找了 fgets 和 sscanf 的每个可能的返回值我似乎无法得到它

防御特征

FIRST printf--------输入应该只是一个大于 0 的数字,EOF 应该返回类似 printf("enter a number--bye!") 的消息,所以我尝试过

while( sscanf(buffer, "%d", &num) ==1 && num > 0 )

但如果输入类似 3dadswerudsad 的内容,它仍然有效

此外,当用户为 vector 输入 3 个值时,如果为 vector 输入了 3 个 double 以外的任何值,程序应该终止并显示一条消息,所以我尝试了

while( sscanf(buffer2, "%lf %lf %lf", &xin, &yin, &zin) ==3 )

但它不会检查这些不正确的输入!!

我要疯了

最佳答案

以下代码:

  • 编译干净
  • 展示了几个错误检查的例子

发布的代码引发了一个编译器警告,即在没有 return 语句的情况下到达非 void 函数的末尾(警告需要更正)。
要查看所有警告,请在为 gcc 编译时启用所有警告,使用参数:-Wall -Wextra -Wpedantic

顺便说一句:正确声明结构的荣誉

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

struct vector
{
    double x;
    double y;
    double z;
};

struct vector *array;

// prototypes
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:");
    if( NULL == fgets(buffer, 30, stdin) )
    { // then fgets failed
        perror( "fgets for num vectors failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fgets successful

    if( 1 != sscanf(buffer, " %d", &num) )
    { // then sscanf failed
        perror( "sscanf for num Vectors failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, sscanf failed


    // add validation of num here


    if( NULL == (array = malloc( sizeof(struct vector) * num) ))
    { // then, malloc failed
        perror( "malloc for num Vectors failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful


    for(i=0;i<=num;i++)
    {
        printf("Please enter x y z for the vector:");
        if( NULL == fgets(buffer2,100,stdin) )
        { // then fgets failed
            perror( "fgets for vector values failed" );
            free(array); // cleanup
            exit( EXIT_FAILURE );
        }

        // implied else, fgets successful

        if( 3 != sscanf(buffer2, " %lf %lf %lf", &xin, &yin, &zin) )
        { // then sscanf failed
            perror( "sscanf for vector values failed" );
           free(array); // cleanup
            exit( EXIT_FAILURE );
        }

        // implied else, sscanf successful

        array[i].x = xin;
        array[i].y = yin;
        array[i].z = zin;
    } // end for

    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]));
    } // end for

    free(array); // cleanup

    return(0);
} // end function: main

关于c - 如何处理用户输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862739/

相关文章:

c - realloc() 如何工作?

C 列表的列表

php - PHP 数据结构书籍

wpf - 本地化 ExceptionValidationRule

将字符串十进制转换为十六进制十进制

c++ - 如何检查 tiff 文件的无效格式错误

java - Java 中常用的数据结构有哪些?

iphone - iPhone网络SSID

reactjs - NextJS 处理 "Server Error"和 "Client side error"的最佳实践

objective-c - 如何从 C 中的控制台接受 "only characters"或 "only digits"?