首页 > 解决方案 > 试图用 strtol 将 str 更改为 int,但它给出了不同的值

问题描述

我的输入文件如下所示:

Harry potter
9403133410 // his ID (this number changes to different one)

这是代码:

void get(){
    FILE* file;
    int i = 0;
    char load[50];
    long x;
    char *nac;
    file = fopen("konferencny_zoznam.txt", "r");
    while (fgets(load, sizeof load, subor) != NULL){
        if (i == 0){
            printf("Prezenter: %s", load);
        }
        if (i == 1){
            x = strtol(load, &nac, 15); //trying to change 9403133410 to int, but it gives me different value
            printf("%ld", x);
            printf("Rodne Cislo: %s", load);
        }
        if (i == 2){
            printf("Kod prezentacnej miestnosti: %s", load);
        }
        if (i == 3){
            printf("Nazov prispevku: %s", load);
        }
        if (i == 4){
            printf("Mena autorov: %s", load);
        }
        if (i == 5){
            printf("Typ prezentovania: %s", load);
        }
        if (i == 6){
            printf("Cas prezentovania: %s", load);
        }
        if (i == 7){
            printf("Datum: %s", load);
        }
        if (i == 8){
            printf("\n");
        }
        i++;
        if (i == 9){i = 0;}
        }
}

我需要该整数来创建错误,例如 ID 不能被 2 或 6 整除。

标签: c

解决方案


x = strtol(load, &nac, 15);

首先,这是读取一个以 15 为底的数字。假设您实际上想要以 10 为底,这应该是:

x = strtol(load, &nac, 10);

接下来,9403133410b10 太大而无法放入 32 位整数。 long不保证大于(在 Windows 上不是),因此您应该使用long long。您还需要打电话strtoll来阅读它并使用%lld它来打印它。

long long x;
...

x = strtoll(load, &nac, 10);
printf("%lld", x);

推荐阅读