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

1.setprecision()函数的使用及头文件?

2.利用getline()怎么读取一行数据,换行符是否读入了?

3.怎么使用串流实现对string字符串的输入输出?

 

写数据到txt文件

//其中的setprecision()函数在头文件iomanip	中
void WriteBeamCoreToFile(string fileName, vector 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 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 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;
	}

读取每一行数据的第一个数

void ReadFirtNum(string fileName, vector& data)
{
	ifstream inFile;
	inFile.open(fileName,ios::in);
	if(!inFile.is_open())//判断文件是否打开
	{
		cout<<"Error opening file" << endl;
	}
	while(!inFile.eof())
	{
		int num;
		string sTmp;
		inFile >> num;
		getline(inFile, sTmp);//略过第一行
		data.push_back(num);
	}
}

 

你可能感兴趣的:(C++)