如何一行一行的读取文件并赋值给变量
展开全部
假设文本文件a.txt存放以下两行内容,需要读入:
3.1425927 56.8
3.1415927 49.5
#include<stdio.h>
void main() { char buffer[256]; double a[2][2]; FILE *fp; int i,j;
if ( fp=fopen("c:\\a.txt","r") ) {
fgets(buffer,256,fp); sscanf(buffer,"%lf%lf",&a[0][0],&a[0][1]);
fgets(buffer,256,fp); sscanf(buffer,"%lf%lf",&a[1][0],&a[1][1]);
fclose(fp);
for ( i=0;i<2;i++,printf("\n") ) for ( j=0;j<2;j++ ) printf("%lf ",a[i][j]); printf("\n");
} else printf("无法打开文件读取。\n");
}
3.1425927 56.8
3.1415927 49.5
#include<stdio.h>
void main() { char buffer[256]; double a[2][2]; FILE *fp; int i,j;
if ( fp=fopen("c:\\a.txt","r") ) {
fgets(buffer,256,fp); sscanf(buffer,"%lf%lf",&a[0][0],&a[0][1]);
fgets(buffer,256,fp); sscanf(buffer,"%lf%lf",&a[1][0],&a[1][1]);
fclose(fp);
for ( i=0;i<2;i++,printf("\n") ) for ( j=0;j<2;j++ ) printf("%lf ",a[i][j]); printf("\n");
} else printf("无法打开文件读取。\n");
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询