Home > Net >  trying to change str to int with strtol, but it gives different value
trying to change str to int with strtol, but it gives different value

Time:11-05

My input file looks like this:

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

Here is the code:

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

I need that integer to create an error, if for example ID cannot be divisible by 2 or 6.

CodePudding user response:

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

First, this is reading a number as base 15. Assuming you actually want base 10, this should be:

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

Next, 9403133410b10 is too large to fit in a 32 bit integer. long is not guaranteed to be larger than that (and on Windows it's not), so you should use long long instead. You'll also need to call strtoll to read it and use %lld to print it.

long long x;
...

x = strtoll(load, &nac, 10);
printf("%lld", x);
  •  Tags:  
  • c
  • Related