a-one a-one - 12 days ago 6
C++ Question

std::getline issue when parsing lines with stringstream library

I am getting an error while trying to parse a stringstream when reading from a file, I cannot seem to figure what the issue is.

the error I am receiving is:

no matching function for call to 'getline'
std::getline(parse_input, intensity, ',');


this repeats for each variable I am trying to parse.

the following is my code:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

int main(int argc, char const *argv[])
{
std::fstream fs;
fs.open("test.dat");

std::string* configuration_record;
std::string temp_count;
size_t no_of_records;

if(!fs.is_open())
{
std::cerr << "File failed to open" << std::endl;
}
else
{
while(!fs.eof())
{
std::getline(fs, temp_count);
no_of_records++;
}
fs.clear();
fs.seekp(0);
}

std::string stimulation_type;
std::string stimulation_name;
double intensity;
double frequency;
double duration;
std::string location;

configuration_record = new std::string[no_of_records];

for(size_t i=0; i<no_of_records; i++)
{
std::getline(fs, configuration_record[i]);
}

for(size_t i=0; i<no_of_records; i++)
{
size_t found;
found = configuration_record[i].find("stim");
if(found != std::string::npos)
{

std::stringstream parse_input(configuration_record[i]);
std::getline(parse_input, stimulation_type, ',');
std::getline(parse_input, stimulation_name, ',');
std::getline(parse_input, location, ',');
std::getline(parse_input, intensity, ',');
std::getline(parse_input, frequency, ',');
std::getline(parse_input, duration, ',');

std::cout << stimulation_name << "," <<location << intensity << "," << frequency << "," << duration
<< std::endl;
}
else
{

std::stringstream parse_input(configuration_record[i]);
std::getline(parse_input, stimulation_type, ',');
std::getline(parse_input, stimulation_name, ',');
std::getline(parse_input, intensity, ',');
std::getline(parse_input, duration, ',');

std::cout << stimulation_name << "," << intensity << "," << duration
<< std::endl;
}
}

return 0;
}

M.M M.M
Answer

The declarations for getline from the manual are:

istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str);

As you see, they accept an istream (stringstream is valid), however the second argument has to be a string, so when you pass double (intensity, frequency and duration), you are calling an inexistent function. you can use a temporary string and then save it to a double, using stod:

std::string temp;
double intensity;
std::getline(parse_input, temp, ',');
intensity= std::stod (temp);