在c++中将csv读入unordered_map

Reading a csv into a unordered_map in C++

本文关键字:unordered map 读入 csv c++ 中将      更新时间:2023-10-16

我试图读取csv文件并将其存储在c++中的哈希映射中。这是我的代码。

 void processList(std::string path, std::unordered_map<std::string, int> rooms){
            std::ifstream openFile(path);
            std::string key;
            int value;
            std::getline(openFile, key, ','); //to overwrite the value of the first line
            while(true)
            {
                if (!std::getline(openFile, key, ',')) break;
                std::getline(openFile, value, 'n');
                rooms[key] = value;
                std::cout << key << ":" << value << std::endl;
            }
    }

我一直得到以下错误

error: no matching function for call to 'getline'
            std::getline(openFile, value, 'n');

std::getline期望std::string作为其第二个参数。你应该传递一个std::string对象到getline,然后使用std::stoi将该字符串转换为int

:

std::string valueString;
std::getline(openFile, valueString, 'n');
auto value = std::stoi(valueString);

std::getline:

template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input,
                                       std::basic_string<CharT,Traits,Allocator>& str,
                                       CharT delim );

std::getline的第二个参数必须是std::string
因此,将value读取为std::string并将其转换为int

std::string _value;
int value;
std::getline(openFile,_value,'n');
value = std::stoi(_value);