1. 程式人生 > >C++讀取txt中用逗號、空格、換行分隔的資料

C++讀取txt中用逗號、空格、換行分隔的資料

使用C++時,免不了要讀取txt檔案中的資料,但是不同的資料格式導致讀取的方式不同,下面進行一個小結。

1.獲取資料夾下的檔名

void getAllFiles(string path, vector<string>& files) {
	//檔案控制代碼  
	long   hFile = 0;
	//檔案資訊  
	struct _finddata_t fileinfo;  //很少用的檔案資訊讀取結構
	string p;  //string類的一個賦值函式:assign(),有很多過載版本
	if ((hFile = _findfirst(p.assign(path).append("\\*.txt").c_str(), &fileinfo)) != -1)
	{
		do
		{
			if ((fileinfo.attrib &  _A_SUBDIR))  //比較檔案型別是否是資料夾
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					files.push_back(p.assign(path).append("/").append(fileinfo.name));
					getAllFiles(p.assign(path).append("/").append(fileinfo.name), files);
				}
			}
			else
			{
				files.push_back(p.assign(fileinfo.name)); //只儲存檔名
			}
		} while (_findnext(hFile, &fileinfo) == 0);  //尋找下一個,成功返回0,否則-1
		_findclose(hFile);
	}

}

2.資料按行排列,如圖所示,將其讀入陣列

void readRowInToArray(fstream &in, string FilePath, int data[ROW]) {
	in.open(FilePath, ios::in);//開啟一個file
	if (!in.is_open()) {
		cout << "Can not find target  file." << endl;
		system("pause");
	}
	string buff;
	int i = 0;
	while (getline(in, buff)) {
		data[i++] = atof(buff.c_str());

	}//end while
	in.close();
	cout << "get data" << endl;
}

3.資料按列排列,如圖所示,將其讀入陣列

void readColumnInToArray(fstream &in, string FilePath, int data[COLUMN]) {
	in.open(FilePath, ios::in);//開啟一個file
	if (!in.is_open()) {
		cout << "Can not find target  file." << endl;
		system("pause");
	}
	char buff;
	int i = 0;
	while (!in.eof()) {
		in >> buff;
		data[i++] = buff - '0';//獲得數字
	}//end while
	in.close();
	cout << "get data" << endl;
}

4.資料為矩陣,如圖所示,將其讀入矩陣

void readInToMatrix(fstream &in, string FilePath, int data[ROW][COLUMN]) {
	in.open(FilePath, ios::in);//開啟一個file
	if (!in.is_open()) {
		cout << "Can not find " << FilePath << endl;
		system("pause");
	}
	string buff;
	int i = 0;//行數i
	while (getline(in, buff)) {
		vector<double> nums;
		// string->char *
		char *s_input = (char *)buff.c_str();
		const char * split = ",";
		// 以‘,’為分隔符拆分字串
		char *p = strtok(s_input, split);
		double a;
		while (p != NULL) {
			// char * -> int
			a = atof(p);
			//cout << a << endl;
			nums.push_back(a);
			p = strtok(NULL, split);
		}//end while
		for (int b = 0; b < nums.size(); b++) {
			data[i][b] = nums[b];
		}//end for
		i++;
	}//end while
	in.close();
	cout << "get  data" << endl;
}