Very basic, trying to read from a text file with numbers and store them in an array

女生的网名这么多〃 提交于 2019-12-12 02:59:01

问题


When I run the program, the numbers I'm getting are completely ridiculous such as -39389014 when the number in the text file is 20. Here is what my text file looks like:

20 20
40 30
80 40
90 20
60 10
18.0

And the Code:

#include <stdio.h>
#define SIZE 5

int main(void){
    FILE *in = fopen("pfile1.txt", "r");
    int x[5], y[5], i;
    double h;

    for (i=0;i<SIZE;++i){
        fscanf(in, "%d %d", &x[i], &y[i]);
    }

    for (i=0;i<SIZE;++i){
        printf("%4d %10d\n", x[i], y[i]);
    }


    fscanf(in, "%lf", &h);
    printf("%lf\n", h);
    fclose(in);

    return(0);
}

回答1:


Make sure that your "pfile1.txt" file is placed next to your project settings. to make sure about the place of your file should be, change the permission of open to "w+". This option will try to open that file or create it if not found. The replace that file with yours. Everything will be work without any problem :)

Just Hint on the fly: Don't make any operation on any pointer unless you make sure that it is not NULL. so, surround your code with to avoid any crashing

if( NULL != in)
{

    for (i=0;i<SIZE;++i){
        fscanf(in, "%d %d", &x[i], &y[i]);
    }

    for (i=0;i<SIZE;++i){
        printf("%4d %10d\n", x[i], y[i]);
    }


    fscanf(in, "%lf", &h);
    printf("%lf\n", h);
    fclose(in);
}


来源:https://stackoverflow.com/questions/36189108/very-basic-trying-to-read-from-a-text-file-with-numbers-and-store-them-in-an-ar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!