数据分别读取的fscanf [英] Data read separately fscanf

查看:194
本文介绍了数据分别读取的fscanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件中读取数字。该文件的格式如下:

  2 4 5 7
3 2 4 7

我试过用的fscanf 来收集所有的数字到换行,并存储在一个阵列和数量与第二行相同的事情。但是从第二行直接进入不会再次启动,并存储在该另一个数组。是否有可能做到这一点使用的fscanf

  INT主要(无效)
{
    FILE * FP;
    为int * VEC =的malloc(sizeof的(INT)* 6);
    为int * vec_2 =的malloc(sizeof的(INT)* 6);
    INT行,我;    FP = FOPEN(vector.txt,R);    对于(i = 0; I<排;我++)//我不知道如何读,直到换行
        的fscanf(FP,%D,&安培; VEC [K]); //这里的第一行存放在数组中    对于(i = 0; I<排;我++)
       的fscanf(FP,%D,&安培; vec_2 [I]); //启动从第二列读取这里    免费(VEC);
    免费(vec_2);
    返回0;
}


解决方案

  INT主要(无效){
    FILE * FP;
    INT COLS = 6;
    为int * vec_1 =的malloc(sizeof的(INT)* COLS);
    为int * vec_2 =的malloc(sizeof的(INT)* COLS);
    INT I,I1,I2;
    焦炭CH;    FP = FOPEN(vector.txt,R);    为(I1 = 0; I1&下; C​​OLS){
        的fscanf(FP,%D%C,&安培; vec_1 [I1 ++],&安培; CH); //格式是有限的。 NUM [\\ t \\ n]
        如果(CH =='\\ n')
            打破;
    }    I2 = 0;
    而(1 ==的fscanf(FP,%D,&安培; vec_2 [12])){
        如果(++ I2 = = COLS)
            打破;
    }
    FCLOSE(FP);
    的printf(第一);
    对于(i = 0; I< I1; ++ I)
        的printf(%d个,vec_1 [I]);
    的printf(\\ n);
    的printf(二:);
    对于(i = 0; I< I2; ++ I)
        的printf(%d个,vec_2 [I]);
    的printf(\\ n);
    免费(vec_1);
    免费(vec_2);
    返回0;
}

I'm trying to read numbers from a file. The file has the following format:

2 4 5 7
3 2 4 7

I tried to do that using fscanf to collect all the numbers up to the newline and store the number in an array and the same with the second line. But proceed directly from the second line does not start again and store this in another array. Is it possible to do this using fscanf?

int main(void)
{
    FILE* fp;
    int *vec = malloc(sizeof(int)*6);
    int *vec_2 = malloc(sizeof(int)*6);
    int row, i;

    fp = fopen("vector.txt","r");

    for(i = 0; i < row; i++) //I don't know how to read until newline
        fscanf(fp, "%d", &vec[k]); //here store the first row in the array

    for(i = 0; i < row; i++)
       fscanf(fp, "%d", &vec_2[i]); //start reading here from the second row

    free(vec);
    free(vec_2);
    return 0;
}

解决方案

int main(void){
    FILE* fp;
    int cols = 6;
    int *vec_1 = malloc(sizeof(int)*cols);
    int *vec_2 = malloc(sizeof(int)*cols);
    int i, i1, i2;
    char ch;

    fp = fopen("vector.txt","r");

    for(i1 = 0; i1 < cols; ){
        fscanf(fp, "%d%c", &vec_1[i1++], &ch);//Format is limited. "num[ \t\n]"
        if(ch == '\n')
            break;
    }

    i2 = 0;
    while(1==fscanf(fp, "%d", &vec_2[i2])){
        if(++i2 == cols)
            break;
    }
    fclose(fp);
    printf("first  : ");
    for(i=0; i<i1; ++i)
        printf("%d ", vec_1[i]);
    printf("\n");
    printf("second : ");
    for(i=0; i<i2; ++i)
        printf("%d ", vec_2[i]);
    printf("\n");
    free(vec_1);
    free(vec_2);
    return 0;
}

这篇关于数据分别读取的fscanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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