简体   繁体   中英

Reading a csv into a unordered_map in C++

I'm trying to read a csv file and store it in a hashmap in C++. Here's my code.

 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;
            }
    }

I keep getting the following error

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

What am I doing wrong.

std::getline expects an std::string as its second parameter. You should pass an std::string object to getline and then use std::stoi to convert that string to int .

Like this:

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 );

The second arg of std::getline must be std::string .
As such, read value as std::string and convert it to int .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM