Search code examples
cc++11int64uint64

Return value from the function varies in c


I wrote a program to fetch all the phone numbers from a file which has other text like at commands and other error from other child process. Here when I try to convert the string to integer using a user-defined function I facing the problem. The converted value stored in the function is not properly returned to main program, instead its returning some unusual and it seems to be the same for every execution. Its surprising me. Can someone advice me.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char lic[128];
unsigned long long sum=0ULL;

unsigned long long stringtoint(char str[])
{
    int i=0;
    sum=0;
    if(str[strlen(str)]!='\0')
        return -1;
        //puts("Im in function");
    while(str[i]!='\0'){
        //printf("- %c -\n",str[i]);
         if(str[i] >= 48 && str[i] <= 57){
             sum = sum*10 + (str[i] - 48);
             //printf("%c and %llu\n",str[i],sum);
         }
         i++;
    }
    if(sum>0)
    printf("\nIn function passed string is %s and integer value is %llu\n",str,sum);
    return sum;
}


FILE *file;     
int main(){
        //long long int inte;
        int64_t inte;        file = fopen("receive","r"); 
        if(file!=NULL)
                while(fscanf(file,"%s",lic)!=EOF){
                        inte = 0;
                        inte=stringtoint(lic);
                        if(inte !=0){
                                printf("In Main %llu is the value of the string %s",inte,lic);
                        if(inte==sum)
                                printf("\n%llu and %llu are same\n",inte,sum);
                }
        }
        printf("\n");
        fclose(file);
        return 0;
}

The result I was getting for this program was given below.

In function passed string is 8939095683 and integer value is 8939095683 In Main 349161091 is the value of the string 8939095683

shameerariff@shameerariff-Satellite-L450:~/Workinffolder/ivr/IVRReporting$ ./datadecoder

In function passed string is 8939095683 and integer value is 8939095683 In Main 349161091 is the value of the string 8939095683

shameerariff@shameerariff-Satellite-L450:~/Workinffolder/ivr/IVRReporting$ ./datadecoder

In function passed string is 8939095683 and integer value is 8939095683 In Main 349161091 is the value of the string 8939095683

Your valuable advice are needed, Thank you in advance for your support.


Solution

  • Point 1. You need to change

    int stringtoint(char str[])
    

    to

    unsigned long long stringtoint(char str[])
    

    Point 2. %lld is not the correct format specifier for unsigned long long. Use %llu