Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast from char * to int loses precision

I am reading numbers from a file.When I try to put each number into an double dimensional array it gives me below error.How do I get rid of this message? My variables: FILE *fp; char line[80];

Error: Cast from char * to int loses precision

Code:-

#include<stdio.h>
#include<string.h>

int main()
{
        FILE *fp;
        char line[80],*pch;
        int points[1000][10];
        int centroid[1000][10];
        float distance[1000][10];
        int noofpts=0,noofvar=0,noofcentroids=0;
        int i=0,j=0,k;

        fp=fopen("kmeans.dat","r");
        while(fgets(line,80,fp)!=NULL)
        {
                j=0;
                pch=strtok(line,",");
                while(pch!=NULL)
                {
                        points[i][j]=(int)pch;
                        pch=strtok(NULL,",");
                        noofvar++;
                        j++;
                }
                noofpts++;
                i++;
        }
        noofvar=noofvar/noofpts;
        printf("No of points-%d\n",noofpts);
        printf("No of variables-%d\n",noofvar);

        return 0;
}
like image 375
Teja Avatar asked Sep 14 '12 02:09

Teja


1 Answers

This is the offending line:

points[i][j]=(int)pch;

You should replace it with

points[i][j]=atoi(pch);

atoi is a function that converts a C string representing an integer number in decimal representation to an int.

like image 146
Sergey Kalinichenko Avatar answered Sep 18 '22 13:09

Sergey Kalinichenko