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

#include<iostream>
#include <string>
#include <vector>
#include <sstream> //字符串转换
#include <fstream>


using namespace std;




int main()
{
	ifstream fin("test.txt");
	string line;
	vector<double> 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<string> 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. 如果读取失败,那么会抛出相对应的异常。

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值