C++读取到文件并存储到数组

读取行

#include
#include
int main()
{
	char a[100],c[100];
	int number=2; //第2行
	int i = number;
	FILE *fp = fopen("data.txt","r");
	if (fp==NULL)
	{
		printf("failed to open file!\n");
		return -1;
	}
	else
	{
		while(fgets(c,100,fp))
		{ 
			//读入每行数据
			i--;
			if(i==0) 
				strcpy(a,c); //读到第三行数据
		}
	}

	printf("第%d行数据:%s\n",number,a);
	fclose(fp);
	return 0;
}

C++读取到文件并存储到数组_第1张图片

用空格分隔读取内容

#include
#include
using namespace std;
int main()
{
	char str[40];
	char c;
	int counter = 0;
	int wordNum = 0;
	string content[20];
	string strName;
	FILE *fp = fopen("data.txt","r");

	if (fp==NULL)
	{
		printf("failed to open file!\n");
		return -1;
	}
	else
	{
		while(1)
		{
			if((c = fgetc(fp)) == EOF)
			{
				str[counter] = '\0';
			    strName = str;
				content[wordNum++] = strName;
				break;
			}
			else if( c == ' ' && (counter > 0))
			{
				str[counter] = '\0';
				counter = 0;
			    strName = str;
				content[wordNum++] = strName;
			}
			else
			{
				str[counter++] = c;
			}
			
		}
		
		for(int j = 0;j<=wordNum;j++)
		{
			cout << content[j] + " ";
		}
	}

}


C++读取到文件并存储到数组_第2张图片

你可能感兴趣的:(C)