简体   繁体   English

从char *转换为int会失去精度

[英]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; 我的变量:FILE * fp; char line[80]; 字符行[80];

Error: Cast from char * to int loses precision 错误:从char *转换为int会失去精度

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

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 . atoi是一个函数,它将代表十进制表示形式的整数的C字符串转换为int

This error occurs while compiling on a 64 bit machine but may not occur on a 32 bit machine as there is difference in size for char* and int . 64 bit machine编译时会发生此错误,但是在char*int大小上存在差异时,在32 bit machine上可能不会发生此错误。

on 64 bit sizeof(char*) is 8 and sizeof(int) is 4 64位上 sizeof(char*)为8并且sizeof(int)为4

on 32 bit sizeof(char*) is 4 and sizeof(int) is 4 32位上 sizeof(char*)为4并且sizeof(int)为4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM