我一直试图从csv文件中读取键/值对,但是无法访问文件中的数据。到目前为止,这是我尝试过的。
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
map<string, string> hash_table;
void load_map(){
// File pointer
ifstream fin;
fin.open("output.csv", ios::in);
// Read the Data from the file
// as String Vector
string temp;
string line;
while (fin >> temp) {
getline(fin, line);
cout << line[0];
//hash_table.insert(line[0], line[1]);
}
}
int main()
{
load_map();
cout << hash_table.size();
cout << hash_table["A12B12C11D11E11F11G10"];
return 0;
}
除了地图大小为0以外,什么都不会打印出来。
答案 0 :(得分:0)
//hash_table.insert(line[0], line[1]);
不是插入键值对的有效方法。 此外,与其使用while(fin >> temp), 替换为
while(getline(fin, line))
然后删除
getline(fin, line);
因为它的功能被替换为
while(getline(fin, line)){...}
然后,通过在代码的正下方插入一些代码,将行分隔为键值(假设csv由','分隔) //hash_table.insert(line[0],line [1]); 喜欢:
string key, value;
stringstream tok(line);
getline(tok, key, ',');
getline(tok, value);
hash_table.insert({key,value});
之后,将包含一些键值对。