如下,有一配置文件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
/*
* readConfig.cpp
* -- 综合运用map和vector读取配置文件内容.
*
* 文件格式:
* 0,3,4,5
* 2,4,5,3
*
*
* Created on: Nov 19, 2019
* Author: xb
*/
#include
#include
#include
#include
#include
#include
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如何去存储读取到的数据。
可能中间的代码还可以优化,如果你有好的建议,欢迎留言。