1.txt
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
2.txt
1 2 3 4 5
2 3 4 5 6
4 5 6 7 8
程序代码:
// C++读取文本到数组.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
int readfile1D()
{
char a[100];
int i;
FILE *fp = fopen("1.txt","r");
if(fp == NULL)
{
printf("文件读取无效.\n");
return -1;
}
for(i = 0; !feof(fp); i++)
fscanf(fp, "%d", &a[i]);
fclose(fp);
for(i=0; i < 20; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
int readfile2D()
{
int a[3][5];
int i,j;
FILE* fp = fopen("2.txt","r");
if(fp == NULL)
{
printf("文件无效");
return -1;
}
for(i=0; i<3; i++)
{
for(j=0; j<5; j++)
{
fscanf(fp,"%d",&a[i][j]);
}
//fscanf(fp,"\n"); 不要也罢
}
fclose(fp);
for(i=0; i<3; i++)
{
for(j=0; j<5; j++)
printf("%d ", a[i][j]);
printf("\n");
}
printf("\n");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
readfile1D();
readfile2D();
return 0;
}
参考:
本文介绍了一种使用C++从文本文件中读取数据并将其存储到一维和二维数组中的方法。通过示例代码展示了如何打开文件、逐行读取数据,并将整数类型的数据存储到数组中。

1636

被折叠的 条评论
为什么被折叠?



