非常基本的,试图从号的文本文件阅读和它们存储在一个数组 [英] Very basic, trying to read from a text file with numbers and store them in an array

查看:92
本文介绍了非常基本的,试图从号的文本文件阅读和它们存储在一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行程序时,我得到的数字是完全荒谬的,如-39389014时,在文本文件中的数字是20.这是我的文本文件的样子:

  20 20
40 30
80 40
90 20
60 10
18.0

而code:

 的#include<&stdio.h中GT;
#定义5号诠释主要(无效){
    FILE *在=的fopen(pfile1.txt,R);
    INT X [5],Y [5],I;
    双H;    对于(i = 0; I<大小; ++ I){
        的fscanf(在%D,&放大器; X [I],&放大器;值Y [i]);
    }    对于(i = 0; I<大小; ++ I){
        的printf(%4D%10d中\\ N中,x [I],值Y [i]);
    }
    的fscanf(在%LF,&安培; H);
    的printf(%LF \\ n,H);
    fclose函数(在);    返回(0);
}


解决方案

请确保您的pfile1.txt文件被放在旁边的项目设置。
以确保有关的地方你的文件应该是,开放的权限更改为W +。此选项将尝试打开文件或创建它,如果没有找到。与你的替换该文件。
一切都将是没有任何问题:)

工作

就提示动态:
不要做任何操作上的任何指针,除非你确定它不为NULL。
因此,环绕你的code。与以避免任何崩溃

 如果(NULL!= IN)
{    对于(i = 0; I<大小; ++ I){
        的fscanf(在%D,&放大器; X [I],&放大器;值Y [i]);
    }    对于(i = 0; I<大小; ++ I){
        的printf(%4D%10d中\\ N中,x [I],值Y [i]);
    }
    的fscanf(在%LF,&安培; H);
    的printf(%LF \\ n,H);
    fclose函数(在);
}

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

解决方案

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

这篇关于非常基本的,试图从号的文本文件阅读和它们存储在一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆