C++容器之vector&map应用——解析配置文件(一)

14 篇文章 1 订阅
6 篇文章 0 订阅

问题引入

如下,有一配置文件1.cac,其中存储的数据为逗号分割的数字点阵,现要求使用map和vector,读取文件内容存入其中。

0,11,8,0
1,8,4,0
2,2,2,0
3,4,4,0
4,4,4,0
5,8,4,0
6,8,4,0
7,0,1,0
8,8,4,0
9,0,1,0

问题分析

仔细一看全都是一样的格式,每行的","看起来有种很熟悉的感觉,有没有想起C的库函数sscanf函数呢。sscanf用于从字符串读取格式化输入,针对这种格式非常明显且固定的字符串,显然是解决问题的不二之选了,我们可以每次读取一行,以逗号分割,将值依次存入vector,再将vector作为value存入map,即构造一个类型为map<int,vector>的map,key可以自己指定。

代码实现

/*
 * readConfig.cpp
 * -- 综合运用map和vector读取配置文件内容.
 *
 * 文件格式:
 * 0,3,4,5
 * 2,4,5,3
 *
 *
 *  Created on: Nov 19, 2019
 *      Author: xb
 */
#include <iostream>
#include <fstream>
#include <errno.h>
#include <string.h>
#include <vector>
#include <map>

using namespace std;

int main() {

	ifstream infile("D:/svnRepository/IEC104SlaveTest/1.cac");
	if (!infile) {
		printf("open file error:%s(errno:%d)\n", strerror(errno), errno);
	}
	string line;//存放每次读取一行的内容
	int a, b, c, d;//对应四列的值
	vector<int> v; 
	map<int, vector<int>> m;
	int count = 0;//可以使用count来作为key值,也可以选择第一列作为key值.这里第一列从0开始,使用哪种方式效果一样
	while (getline(infile, line)) {
		sscanf(line.data(), "%d,%d,%d,%d", &a, &b, &c, &d); //data()将string转为char*
		v.push_back(a);
		v.push_back(b);
		v.push_back(c);
		v.push_back(d);

		m[count] = v;//以行数为key值(从0开始)
		//m[a] = v; //以第一列为key值
		
		v.clear();//每行读完以后清空,存放下一行的值
		count++;
	}

	for (map<int, vector<int>>::iterator it = m.begin(); it != m.end(); it++) {
		cout << " [key] = " << it->first << ",[value] = ";
		for (vector<int>::iterator it_inner = it->second.begin();it_inner != it->second.end(); it_inner++) {
			cout << *it_inner << " ";
		}
		cout << endl;
	}

	return 0;
}

程序输出:

 [key] = 0,[value] = 0 11 8 0 
 [key] = 1,[value] = 1 8 4 0 
 [key] = 2,[value] = 2 2 2 0 
 [key] = 3,[value] = 3 4 4 0 
 [key] = 4,[value] = 4 4 4 0 
 [key] = 5,[value] = 5 8 4 0 
 [key] = 6,[value] = 6 8 4 0 
 [key] = 7,[value] = 7 0 1 0 
 [key] = 8,[value] = 8 8 4 0 
 [key] = 9,[value] = 9 0 1 0 

到这里就可以按照需要从map中取值了,关键是sscanf的使用以及map和vector如何去存储读取到的数据。
可能中间的代码还可以优化,如果你有好的建议,欢迎留言。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值