1、fopen函数可以读取文件,读到的每一行保存在字符数组中,根据空格作为分隔符进行分割。
2、例程:
#include
#include
#define MAXLINE 3
#define MAXCOLUMN 10
void main(void){
FILE *fp; //文件指针
char arr[MAXLINE][MAXCOLUMN]={0}; //定义3行10列的二维数组并初始化
int i = -1;
if((fp=fopen("./test/filename.txt","r"))==NULL){ //打开txt文件
perror("File open error!\n");
return;
}
while((fgets(arr[++i],MAXCOLUMN+1,fp))!=NULL) //读取一行并存到arr数组,百度fgets
printf("%d: ",i); //打印行号
//puts(arr[i]);
char *subarr = strtok(arr[i]," "); //以空格为分隔符从arr[i]中获得字串,百度strtok
while(subarr!=NULL){
data[i][j] = atoi(subarr); //将字串转为int型数据存入data数组
printf("%d\t",data[i][j]); //打印data[i][j
subarr = strtok(NULL," "); //继续获得arr[i]中的字串
j++; //data数组列加一
}
printf("\n");
}
//循环完毕后,所有数据已在data数组中
printf("\n");
fclose(fp); //关闭指针
}
#include
#include
#include
using namespace std;
const unsigned int MAX_LINES = 1024;
int main()
{
ifstream inFile;
string tmpStr("");
string *a = new string[MAX_LINES];
int index = 0;
inFile.open("./code.txt", ios::in);
if (NULL == inFile)
{
cout << "文件打开失败!" << endl;
return 1;
}
while (getline(inFile, tmpStr))
{
a[index] = tmpStr;
index += 1;
}
for (int j = 0; j < index; j++)
{
cout << a[j] << endl;
}
delete [] a;
return 0;
}
FILE *fp
char a[100];
if((fp = fopen("code.txt", "r") )== NULL)
{
cout<<"文件打开失败";
}
else{
for(i=0;!feof(fp);i++)
fscanf(fp,"%s",a[i]);
}
定义文件指针fp,读取code.txt中字符存入字符数组a[i]中,直到文件结束。
#include
#include
using namespace std;
const int MAX_LINES = 100;
const int MAX_CHARS_PER_LINE = 20;
int main()
{
char str[MAX_LINES][MAX_CHARS_PER_LINE];
ifstream ifs("code.txt");
int i = 0;
while (ifs>> str[i])
{
i++;
}
for (int j = 0; j < i; j++)
{
cout<< str[j]<}
system("pause");
}