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

Tej*_*eja 14 c casting compiler-errors

我正在从一个文件中读取数字.当我尝试将每个数字放入一个双维数组时,它给出了我的错误.我如何摆脱这个消息?我的变量:FILE*fp; char line [80];

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

码:-

#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;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 22

这是违规行:

points[i][j]=(int)pch;
Run Code Online (Sandbox Code Playgroud)

你应该用它替换它

points[i][j]=atoi(pch);
Run Code Online (Sandbox Code Playgroud)

atoi是一个函数,它将表示十进制表示中的整数的C字符串转换为int.

  • 值得注意的是“atoi”位于 &lt;cstdlib&gt; 库中 (2认同)

小智 12

编译时发生此错误,64 bit machine但可能不会发生,32 bit machine因为char*和的大小不同int.

64位 sizeof(char*)是8并且sizeof(int)是4

32位 sizeof(char*)是4并且sizeof(int)是4

  • +1,这个症状就是我要找的。我正在为 64 位机器构建一个开源库,遇到了类似的错误,但不确定。 (2认同)