C++ 從TXT文件中一行一行的讀取數據並且保存到數組中

C++ 從TXT文件中一行一行的讀取數據並且保存到數組中

 

這裏使用了vector數組,以及new 動態數組,組成二維數組。

fscanf(fp,"%lf", &rowArray[i]):獲取文件中數據,並將其賦值給 rowArray[i],"%lf" 爲雙精度

fscanf函數詳解,參考:https://blog.csdn.net/zhuiqiuzhuoyue583/article/details/107151385

 

#include <fstream>
#include <string>
#include <iostream>
#include <vector>
using namespace std;

// 功能:將filename 中的數據(共cols列)讀取到_vector中,_vector可視爲二維數組
int read_scanf(const string &filename, const int &cols, vector<double *> &_vector)
{
	FILE *fp = fopen(filename.c_str(), "r");
	bool flag = true;
	int i = 0;
	if (!fp) 
	{ 
		cout << "File open error!\n"; 
		return 0; 
	}

	while (flag)
	{
		double *rowArray = new double[cols]; //new一個double類型的動態數組

		for (i = 0; i < cols; i++) //讀取數據,存在_vector[cols]中
		{
			if (EOF == fscanf(fp,"%lf", &rowArray[i]))
			{ 
				flag = false; 
				break; 
			}
			//輸出rowArray存入的數據
			//cout << rowArray[0] << " " << rowArray[1] << " " << rowArray[2] << " " << rowArray[3] << endl;
		}
		if (cols == i) //將txt文本文件中的一行數據存入rowArray中,並將rowArray存入vector中
			_vector.push_back(rowArray);
	}
	fclose(fp);
	return 1;
}
int  main()
{
        string file ="test.txt";
	//txt文件中有4列
	int columns = 4;
	vector<double *> output_vector;
	if (!read_scanf(file, columns, output_vector))
	{
		return 0;
	}
		
	//output_vector可視爲二維數組;輸出數組元素:
	int rows = output_vector.size();
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < columns; j++) 
		{ 
			cout << output_vector[i][j] << " "; 
		}
		cout << endl;
	}

	system("pause");
	return 0;
}

test.txt中的數據爲:

8 0 3 2
8 0 3 25

輸出結果爲:

 

fscanf函數詳解,參考:https://blog.csdn.net/zhuiqiuzhuoyue583/article/details/107151385 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章