C++读写文件相关(包括一行行读取数据)的函数

写数据到txt文件

//其中的setprecision()函数在头文件iomanip	中
void WriteBeamCoreToFile(string fileName, vector<Point2f> pCenters)
	{
		ofstream outFile;
		outFile.open(fileName);
		int nPointsNum = pCenters.size();
		for (int i = 0; i < nPointsNum; i++)
		{
			outFile << fixed << setprecision(5) << pCenters[i].x << " " << pCenters[i].y << "\n";
		}
		outFile.close();
	}

读数据到变量,一行一行的读取(灵活):

bool CBeamCore::CalActualDis(Mat srcImg, Point2f& pCenter, string calibrateFile, double & dActualDis, Mat& imgShow)
	{
		CalCore(srcImg, pCenter, imgShow);
		double dX = pCenter.x;
		CubicSplineInterpolation cubicSpline;

		//读取多项式信息
		CubicSplineCoeffs *cubicCoeffs;
		vector<double> dBeamsX;
		ifstream inFile(calibrateFile);
		int i = 0;
		while (!inFile.eof())
		{
			string buffTmp;
			double dTmp = 0.0;
			getline(inFile, buffTmp);//读取第一行
			stringstream stringIn(buffTmp);//使用串流实现对string的输入输出操作
			while (stringIn >> dTmp)
				dBeamsX.push_back(dTmp);
		
			cubicCoeffs = new CubicSplineCoeffs(dBeamsX.size() - 1);
			//读取后续行
			buffTmp.clear();
			int nCoeffIndex = 0;
			while (getline(inFile, buffTmp))
			{
				stringstream stringCoeffs(buffTmp);
				vector<double> abcdTmp;
				while (stringCoeffs >> dTmp)				
					abcdTmp.push_back(dTmp);			
			
				cubicCoeffs->a[nCoeffIndex] = abcdTmp[0];
				cubicCoeffs->b[nCoeffIndex] = abcdTmp[1];
				cubicCoeffs->c[nCoeffIndex] = abcdTmp[2];
				cubicCoeffs->d[nCoeffIndex] = abcdTmp[3];
				nCoeffIndex++;			
			}
		}
		inFile.close();
		if (!cubicSpline.cubicSplineInterpolation2(cubicCoeffs, dBeamsX, dX, dActualDis))
			return false;
		return true;
	}

猜你喜欢

转载自blog.csdn.net/vict_wang/article/details/81174004