C++知识点(7)_istringstream文件流

在阅读udacity的粒子滤波的代码时,发现读取地图数据的代码(从文件中读取数据存放到自定义的数据结构中)写得还不错,后续可能会在工程中用上,在这里记录下来,以作记录。
首先它定义了地图数据结构:

class Map {
public:
	struct single_landmark_s
	{
		int id_i ; // Landmark ID
		float x_f; // Landmark x-position in the map (global coordinates)
		float y_f; // Landmark y-position in the map (global coordinates)
	};
	std::vector<single_landmark_s> landmark_list ; // List of landmarks in the map
};

具体数据文件存放在一个map_data.txt中
92.064 -34.777 1
61.109 -47.132 2
17.42 -4.5993 3
-7.1285 -34.54 4
232.32 32.032 5
177.43 28.083 6
286.89 18.159 7
274.37 31.197 8
主函数中去调用read_map_data()函数:

  // Read map data
  Map map;
  if (!read_map_data("../data/map_data.txt", map)) 
  {
	  cout << "Error: Could not open map file" << endl;
	  return -1;
  }

然后我们来看看read_map_data()的具体实现:

/* Reads map data from a file.
 * @param filename Name of file containing map data.
 * @output True if opening and reading file was successful
 */
inline bool read_map_data(std::string filename, Map& map) 
{
	// Get file of map:
	std::ifstream in_file_map(filename.c_str(),std::ifstream::in);
	// Return if we can't open the file.
	if (!in_file_map) {
		return false;
	}
	
	// Declare single line of map file:
	std::string line_map;

	// Run over each single line:
	while(getline(in_file_map, line_map)){

		std::istringstream iss_map(line_map);

		// Declare landmark values and ID:
		float landmark_x_f, landmark_y_f;
		int id_i;

		// Read data from current line to values::
		iss_map >> landmark_x_f;
		iss_map >> landmark_y_f;
		iss_map >> id_i;

		// Declare single_landmark:
		Map::single_landmark_s single_landmark_temp;

		// Set values
		single_landmark_temp.id_i = id_i;
		single_landmark_temp.x_f  = landmark_x_f;
		single_landmark_temp.y_f  = landmark_y_f;

		// Add to landmark list of map:
		map.landmark_list.push_back(single_landmark_temp);
	}
	return true;
}

把数据放到了vecotr的结构体数据类型中,这种方法在工程中很常用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值