如何从带有文本的文件中读取数据 [英] How to read data from a file with text

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

问题描述

我想从包含一些文本的数据文件test.dat中提取数据。该文件如下:



 nx = 200,ny = 200 
cow
1 2
5 6
4 9
2 0
3 8
goat
1 2
3 2
2 4







我写的代码如下:





  int  A [ 10 ] [ 10 ]; 
char buff [ 100 ];

FILE * in ;
in = fopen( test.dat r);

int i,j;

fgets(buff, 100 in );
fgets(buff, 100 );

for (i = 1 ; i< = 5 ; i ++)
{ for (j = 1 ; j< = 2 ; j ++)
{fscanf( in %d,& A [i] [j]);}}

fgets(buff, 100 in );
put(buff);

for (i = 6 ; i< = 8 ; i ++)
{ for (j = 1 ; j< = 2 ; j ++)
{
fscanf( in %d,& A [i] [j]);
}
}
fclose( in );



for (i = 1 ; i< = 8 ; i ++)
{
for (j = 1 ; j< = 2 ; j ++)
{
printf( %d \ t,A [i] [j]);
}
printf( \ n);
}





我得到以下输出:

< pre lang =text> 1 2
5 6
4 9
2 0
3 8
0 268501009
0 2
0 4200638







前五行是好的,但最后3行是垃圾。请建议需要做什么。

解决方案

我会写的(警告,没有执行错误检查):

  #include   <   stdio.h  >  
# include < stdlib.h >

#define BUFSIZE 100
#define SIZE 10

int main()
{
char buf [BUFSIZE];
int a [SIZE] [ 2 ];

FILE * fp = fopen( test.dat r);

int count = 0 ;
while (fgets(buf,BUFSIZE,fp))
{
if (sscanf(buf, %d%d,& a [count] [ 0 ],& a [count] [ 1 ])== 2
count ++;
}

int n;
for (n = 0 ; n< count; ++ n)
{
printf( %d%d \ n,a [n] [ 0 ],a [n] [ 1 ]);
}

fclose(fp);

return 0 ;

}


I want to extract data from a data file "test.dat" which contains some text as well. The file is as follows:

nx=200, ny=200
cow
1	2
5	6
4	9
2	0
3	8
goat
1	2
3	2
2	4




I have written the code as follows:


int A[10][10];
char buff[100];

FILE *in;
in=fopen("test.dat","r");

int i,j;

fgets(buff,100,in);
 fgets(buff,100,in);   

 for(i=1;i<=5;i++)
    {for(j=1;j<=2;j++)
        {fscanf(in,"%d",&A[i][j]);}}
        
      fgets(buff,100,in);   
      puts(buff);
    
for(i=6;i<=8;i++)
    {for(j=1;j<=2;j++)
        {
		  fscanf(in,"%d",&A[i][j]);
		}
	}	   
        fclose(in);

	
	
for (i=1;i<=8;i++)
    {
    for(j=1;j<=2;j++)
       {
           printf("%d\t",A[i][j]);
       }
           printf("\n");
    }



I get the following output:

1	2	
5	6	
4	9	
2	0	
3	8	
0	268501009	
0	2	
0	4200638	




The first five lines are ok, but the last 3 lines are junk. Please suggest what needs to be done.

解决方案

I would have written instead (warning, no error-checking performed):

 #include <stdio.h>
 #include <stdlib.h>

 #define BUFSIZE 100
 #define SIZE 10

int main()
{
  char buf[BUFSIZE];
  int a[SIZE][2];

  FILE * fp = fopen("test.dat", "r");

  int count = 0;
  while (fgets(buf, BUFSIZE, fp))
  {
    if (sscanf(buf, "%d %d", &a[count][0], &a[count][1]) == 2)
      count++;
  }

  int n;
  for (n=0; n<count; ++n)
  {
    printf("%d %d\n", a[n][0], a[n][1]);
  }

  fclose(fp);

  return 0;

}


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

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