C++ 文件读取(按行读取,每行以空格隔开,并转成double)

C++ 文件读取(按行读取,每行以空格隔开,并转成double),第1张

#include
#include 
#include 
#include  //字符串转换
#include 


using namespace std;




int main()
{
	ifstream fin("test.txt");
	string line;
	vector location_1, location_2, location_3;

	if (fin)
	{
		while (getline(fin, line)) //按行读取到line_info中 
    	{
			if (line.size() == 0)
			{
				break;   //循环体内手动的进行空行的判断
			}
			//cout << "line:" << line << endl;
			istringstream sin(line); //create string input object
			vector Waypoints;
			string info;

			while (getline(sin, info, ' '))
			{
				//cout << "info:" << info << endl;
				Waypoints.push_back(info);
			}

			string x1_str = Waypoints[0];
			string x2_str = Waypoints[1];
			string x3_str = Waypoints[2];
			// cout<< "x_str" << x_str << endl;
			// cout<< "y_str" << y_str << endl;

			double x1, x2, x3;
			stringstream sx1, sx2, sx3; //transform string to double

			sx1 << x1_str;
			sx2<< x2_str;
			sx3 << x3_str;
			sx1 >> x1;
			sx2 >> x2;
			sx3>> x3;
			location_1.push_back(x1);
			location_2.push_back(x2);
			location_3.push_back(x3);
		}
	}
	else
	{
		cout << "no such file" << endl;;
	}
	fin.close();
	for (int j = 0; j < location_1.size(); j++)
	{
		cout << "location_1[" << j << "]: " << location_1[j] << " ";
		cout << "location_2[" << j << "]: " << location_2[j] <<" " ;
		cout << "location_3[" << j << "]: " << location_3[j] <<" " ;
		cout << endl;
	}
	return 0;
}

 处理istream流额时候,getline()的返回值是这样的:
只要可以读到文件内容(包括空行),返回值就一直是True. 如果读取失败,那么会抛出相对应的异常。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/921616.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存