如何从文本文件中读取多个数字 [英] How to read multiple number from a text file

查看:168
本文介绍了如何从文本文件中读取多个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的代码,我不断收到分段错误。
如何格式化这段代码从文件中读取一组数字?



我的输入如下所示:82,46,71,56,44 ,12,100,62,67,64,65,62,39,68,68,90,78,57,76,45,82等等。

  #include< stdio.h> 

int main()
{
FILE * input = fopen(input.txt,r);

int line [7];
int store = 0,读取;
$ b $ if(!input)
{
printf(Error:Filename \input.txt \not found!\\\
);
}

store = 0;
while(fscanf(input,%d,& read)!= EOF)
{
line [store] = read;
store ++;

$ b $ printf(%d%d%d%d%d%d%d \ n,行[0],行[1],行[2],行行[3],行[4],行[5],行[6]);
return(0);


解决方案

  while(store< sizeof(line)/ sizeof(int)&& fscanf(input,%d & read)!= EOF)

看起来您在输入中有更多数字,有空间。


So this is my code and I keep getting segmentation faults. How can I format this code to read a set of numbers from a file?

My input looks like this: 82, 46, 71, 56, 44, 12, 100 62, 67, 64, 65, 62, 39, 68 68, 90, 78, 57, 76, 45, 82 etc

#include <stdio.h>

int main ()
{
    FILE *input = fopen("input.txt", "r");

    int line[7];
    int store = 0, read;

    if(!input)
    {
        printf("Error: Filename \"input.txt\" not found!\n");
    }

    store = 0;
    while(fscanf(input, "%d", &read) != EOF)
    {            
        line[store] = read;                 
        store++;
    }

    printf("%d %d %d %d %d %d %d\n", line[0], line[1], line[2], line[3], line[4], line[5], line[6]); 
    return(0);
}

解决方案

Change your while loop condition into:

while( store < sizeof(line)/sizeof(int) && fscanf(input, "%d", &read) != EOF)

looks like you have more numbers in the input then you have space for.

这篇关于如何从文本文件中读取多个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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