关于断言和中止陷阱6

时间:2016-02-07 02:37:50

标签: c debugging

这是一个主要用于货币兑换计算的程序。但问题是,当我编译并运行时,它说

断言失败:(argc == 4 || argc == 2),函数main,文件test.c,第24行。 中止陷阱:6

感谢!!!!

void convert(int type, double amount, double rate);

int get_type(char* string);

void convert(int type, double amount, double rate) {
    printf("%.2f %s is %.2f %s\n", amount, type == 1 ? "dollars" : "euros", amount * rate, type == 1 ? "euros" : "dollars");
}

int get_type(char* string) {
    int i, c;
    for (i = 0, c = string[0]; c != '\0'; c = string[i]) {
            if (c >= 'A' && c <= 'Z') {
                    string[i] -= 'A' - 'a';
            }
    }
    return !strcmp(string, "dollar") ? 1 : !strcmp(string, "euro") ? 2 : 0;
}   

int main(int argc, char** argv) {
    assert(argc ==4 || argc == 2);
    if (argc == 4) {
            int type = get_type(argv[1]);
            if (type == 0) {
                    printf("%s is an invalid currency type. Use dollar or euro.\n", argv[1]);
                    return 1;
            }
            convert(type, atof(argv[2]), atof(argv[3]));
    }

    if (argc == 2) {
            FILE* fd;
            fd = fopen(argv[1], "r");
            if (fd == NULL) {
                    printf("Could not open %s\n", argv[1]);
                    return 1;
            }
            char* typestring = (char*)malloc(16 * sizeof(char));
            double amount, rate;
int matches, type;

            while (!feof(fd)) {
                    matches = fscanf(fd, "%s %lf %lf\n", typestring, &amount, &rate);
                    if (matches != 3) {
                            printf("Line was not formed correctly.\n");
                            continue;
                    }
                    type = get_type(typestring);
                    if (type == 0) {
                            printf("%s is an invalid currency type. Use dollar or euro.\n", typestring);
                            continue;
                    }
                    convert(type, amount, rate);
            }
            free(typestring);
    }


    if (argc == 2 && argc != 4) {
            printf("Usage:\n\tmoney-exchange [dollar|euro type] [double amount] [double rate]\n");
            printf("\tmoney-exchange [FILE]\n");
            printf("Examples:\n\tmoney-exchange dollar 10.50 0.92\n");
            printf("\tmoney-exchange euro 5.99 1.09\n");
            printf("\tmoney-exchange prices.txt\n");
            return 1;
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

运行时,您没有为程序提供正确数量的参数。您必须提供一个或三个参数(当然,额外的一个是命令本身)。

换句话说,你应该像以下那样运行它:

money-exchange inputfile.txt

或:

money-exchange dollar 42 0.9

顺便说一句,顺便说一句,我并不是真正使用assert的忠实粉丝,因为它们通常在生产代码中被禁用。更好的是代码只需检查argc并退出并显示错误消息。这样,您可以确定在所有情况下都会检查它:

if ((argc != 2) && (argc != 4)) {
    fprintf (stderr, "What the heck are you thinking?");
    return 1;
}

所以在这种情况下,因为你实际上代码可以完成这个但是assert在它到达那个点之前退出程序,阻止它显示使用细节如果你错误地称呼它。

我会放弃assert,除了argc检查之外,它不会给你任何保护。